【发布时间】:2015-03-28 00:23:52
【问题描述】:
我正在编写一个程序来在 stl::list 容器中添加货币价值。我如何解析并将这些值加在一起?谢谢。
我要使用的代码如下 - 我在底部添加了累积。
void readFile()
{
string line, nuMoney, money, 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('.');
// remove commas.
line.erase (remove(line.begin(), line.end(), ','), line.end());
money = line.substr(dollarSign+1);
//cout << money << endl;
double MONEYS = atof(money.c_str());
//cout << fixed << setprecision(2) << MONEYS << '\n';
list<double> acct;
acct.push_back(MONEYS);
}
int sum = accumulate(acct.begin(), acct.end(), 0);
cout << "SUM: " << sum << endl;
}
【问题讨论】:
-
有人已经为你写好了算法:
std::accumulate -
@WhozCraig 它不起作用。
-
举例说明你想做什么。
-
@JohnnyTran 为我工作:ideone.com/eqmPHd
-
在@Atomic_alarm 上面发布的代码中使用它
标签: c++ list templates stl std