我正在编写一个程序来在stl :: list容器中添加money的值。我怎么能解析并将值一起添加?感谢。
我想要使用的代码如下 - 我在底部添加了累积。
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;
}
答案 0 :(得分:2)
这显示了如何对列表的内容进行求和
#include <list>
#include <algorithm>
#include <numeric>
int main()
{
std::list<int> myList;
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
int result = std::accumulate(std::begin(myList), std::end(myList), 0);
std::cout << result; // Prints 10 on screen
}