在我的程序中,我试图用“$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