c ++ 如何阻止我的循环两次吐出最后一个输入

c++ How do I stop my loop from spitting out the last input twice

本文关键字:两次 输入 最后一个 何阻止 我的 循环      更新时间:2023-10-16

我正在做一个银行程序,在我的存款函数中,我有以下代码,它从文本文件中读取并将金额存储到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<<"tt"<<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-05-24 100

12-05-30 300

12-01-07 -300

控制台输出如下所示

托尼·加迪斯

12-05-24 100

12-05-30 300

12-01-07 -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<<"tt"<<amount<<endl;
        famount+=amount;
    }
}
cout<<famount;

之前,如果getline(file, line)读取最后一行为空,它将返回 true 并输入 while 块。稍后,您的iss >> date >> amount将在 while 块内失败,因为stringstream将仅设置为该空行,因此您将重复输出之前该行的日期和金额。

请记住,如果您必须检查eof()几乎总是有问题......