1

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

12 年 5 月 30 日 300

2012 年 7 月 1 日 -300

//控制台输出看起来像这样

托尼·加迪斯

12 年 5 月 24 日 100

12 年 5 月 30 日 300

2012 年 7 月 1 日 -300

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

-200 //应该是100

我能做些什么来纠正这个问题,为什么会这样。提前致谢。

4

1 回答 1

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()几乎总是有问题...

于 2013-10-30T21:27:59.243 回答