我对此代码有疑问。您能否帮助我找出为什么它不将新的捐赠总额(总计)保存到文件(donation_total.txt)中?应该注意的是,文件中保存的默认值为零,但每次迭代都会保留默认值。我需要每次将新值保存在最后一行。
谢谢
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
fstream records;
records.open("donation_total.txt", ios_base::in | ios_base::out | ios_base::app);
if (records.is_open())
{
cout << "The record file is open!" << endl;
string line;
while (!records.eof())
{
getline(records, line);
}
int total = stoi(line);
cout << "Total donation is: "<<total << endl;
cout << "Is there any new record?" << endl;
string str,newname;
stringstream field;
string name;
int donation;
getline(cin , str);
while (str=="Yes" | str=="yes")
{
cout << "Enter name and donation value: ";
getline(cin, newname);
field.str(newname);
field >> name >> donation;
total += donation;
field.clear();
cout << name << " donates " << donation << "$" << endl;
cout << "Total donation is: " << total << endl;
records << endl << total;
cout << "Is there any new record?" << endl;
getline(cin, str);
}
}
else
{
cerr << "Could not find the file!" << endl;
}
records.close();
return 0;
}
答案 0 :(得分:0)
您的程序有很多逻辑错误。输入没有捐赠金额的名称时,它将使用先前捐赠的值。
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main()
{
fstream records;
records.open("donation_total.txt", ios_base::in | ios_base::out | ios_base::app);
if (records.is_open())
{
cout << "The record file is open!" << endl;
string line;
while (getline(cin, line))
{
int total = stoi(line);
cout << "Total donation is: "<<total << endl;
cout << "Is there any new record?" << endl;
string str,newname;
stringstream field;
string name;
int donation;
getline(cin , str);
while (str=="Yes" || str=="yes")
{
cout << "Enter name and donation value: ";
getline(cin, newname);
field.str(newname);
field >> name >> donation;
total += donation;
field.clear();
cout << name << " donates " << donation << "$" << endl;
cout << "Total donation is: " << total << endl;
records << endl << total;
cout << "Is there any new record? ";
getline(cin, str);
}
break;
}
}
else
{
cerr << "Could not find the file!" << endl;
}
records.close();
return 0;
}
How to Run External Commands and Programs Locally and Remotely from JMeter