我正在做一个银行程序,在我的存款功能中,我有以下代码,它从一个文本文件中读取并将金额存储到 famount 中。 唯一的问题是,当我运行程序并输出 famount 时,前面的行与上面的行具有完全相同的数据。
这是一段代码。
file>>firstname>>lastname;
cout<<endl<<firstname<<" "<<lastname<<endl;
string line;
while (getline(file, line))
{
//stringstream the getline for line string in file
istringstream iss(line);
file>>date>>amount;
iss >> date >> amount;
cout<<date<<"\t\t"<<amount<<endl;
famount+=amount;
// I tried to use this to stop reading after
// to the file ends but it still reads the last
// data on the file twice.
if(file.eof()){
break;
}
}
cout<<famount;
文本文件如下所示:
托尼·加迪斯
12 年 5 月 24 日 100
05/30/12 300
07/01/12 -300
//控制台输出如下所示
托尼·加迪斯
12 年 5 月 24 日 100
05/30/12 300
07/01/12 -300
07/01/12 -300//这不应该在这里!!!!!!
-200//结果应该是100
我能做些什么来纠正这个问题,为什么会这样。 提前致谢。
最佳答案
您可能希望将代码更改为:
file>>firstname>>lastname;
cout<<endl<<firstname<<" "<<lastname<<endl;
string line;
while (getline(file, line))
{
//stringstream the getline for line string in file
istringstream iss(line);
// file>>date>>amount; // that line seems a bit off...
if (iss >> date >> amount;) // it would have failed before when line was an empty last line.
{
cout<<date<<"\t\t"<<amount<<endl;
famount+=amount;
}
}
cout<<famount;
之前if getline(file, line)
读到一个空的最后一行,它会返回true 并进入while block 。稍后您的 iss >> date >> amount
将在 while block 内失败,因为 stringstream
将仅设置为该空行,因此您将重复输出日期和金额来自前一行。
请记住,如果您必须检查 eof()
,几乎总会有问题...
关于c++如何阻止我的循环吐出最后一次输入两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19693997/