在我的程序中,即时通讯试图读取带有“ $ 876,725.38”这样的钱的文件,我能够删除逗号和美元符号,并且现在尝试使用atof将字符串转换为双精度,但是即时通讯出现的问题是在打印后MONEYS
转换后,我得到了其中大部分的句点之前的所有内容,但有些在句点之前少于6位数的确在句点之后打印了一位或两位数。如果有人对此有解决方案,将不胜感激。我是C ++的新手,需要帮助。谢谢!
主要问题:从字符串转换为双精度,十进制后的数据不会打印。
void readFile()
{
string line, nuMoney, munney, cents;
unsigned long dollarSign, period;
ifstream myfile("MONEY.txt");
int numLines = countLines("MONEY.txt");
//cout << "NUMLINES: " << numLines << endl;
if (!myfile.is_open())
{
cout << "ERROR: File could not be opened." << endl;
}
for (int i=0; i < numLines-1; i++)
{
getline(myfile, line, '\n');
dollarSign = line.find('$');
period = line.find('.');
line.erase (remove(line.begin(), line.end(), ','), line.end()); //remove commas
munney = line.substr(dollarSign+1);
//cout << munney << endl;
//cents = line.substr(period);
//cout << "Cents: " << cents << endl;
//double CENTUS = atof(cents.c_str());
//cout << "CENTUS: " << CENTUS << endl;
double MONEYS = atof(munney.c_str());
cout << MONEYS << endl;
list<double> acct;
acct.push_back(MONEYS);
}
}
样本输出:
937380
404261
814158
30218.1
69340.1
479891
517241
7203.55
975619
59219.4
900052
539774
336799
347700
532466
83496.8
您必须告诉输出流您想要点后的2位数字的固定精度:
#include <iomanip>
// ...
std::cout << std::fixed << std::setprecision(2) << MONEYS << '\n';
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句