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

时间:2013-10-30 21:19:25

标签: c++ visual-studio loops fstream

我正在做一个银行业务程序,在我的存款功能中,我有以下代码从文本文件中读取并将金额存储到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;

文本文件如下所示:

Tony Gaddis

05/24/12 100

05/30/12 300

07/01/12 -300

//控制台输出如下所示

Tony Gaddis

05/24/12 100

05/30/12 300

07/01/12 -300

07/01/12 -300 //这不应该在这里!!!!!

-200 //应该导致100

我该怎么做才能纠正这个问题,为什么会发生这种情况。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可能希望将代码更改为:

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;

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

请记住,如果您必须检查eof(),那么几乎总会出现问题......