2013-10-30 41 views
1

我正在做一个银行业务程序和我的存款功能我有下面的代码,它从文本文件中读取并将数量存储到famount中。 唯一的问题是,当我运行该程序并输出了命令时,先前的行与上面的行具有完全相同的数据。C++如何阻止我的循环吐出最后一次输入两次

这是一段代码。

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; 

文本文件看起来像这样:

托尼·盖迪斯

05/24/12 100

05/30/12 300

07/01/12 - 300

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

托尼·盖迪斯

05/24/12 100

05/30/12 300

07/01/12 -300

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

-200 //应该导致100

我能做些什么来纠正这一点,为什么它的发生。 在此先感谢。

+3

“咕哝咕哝两次” - >'EOF()'滥用。不要使用'eof()'。这个不成立。请检查您的输入操作。 –

+2

'文件>>日期>>金额; iss >> date >> amount;'你从文件中提取两次,从stringstream中提取一次。为什么? – jrok

+0

我仍然在试着看这个代码如何用那个输入生成那个输出。 ..我仍然没有看到它。如果有什么,我希望它输出*少*数据比你想要的,没有更多的,没有其他的具体原因,除了多余的'文件>>日期>>数量* *内循环,你明显忽略删除时添加每在线处理。等等...现在我明白了。如果 – WhozCraig

回答

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,并输入而块。之后您的iss >> date >> amount将在while块内失败,因为stringstream将仅设置为该空行,因此您需要重复输出之前行的日期和金额。

请记住,如果你要检查eof()有几乎总是有些不妥......

+0

+1这显然是为每行处理做到这一点的正确方法,并分析了如何导致重复的最后一行(即使没有'file.eof()'在原始代码中调用它) ,是一个有趣的大脑cersise。 – WhozCraig

+0

“// file >> date >> amount; //该行似乎有点偏离......” - Tribse。大声笑是啊,我试图教自己的代码,所以我犯了这样的随机错误。但我非常感谢你的帮助。谢谢:) – user2934783

+0

@ user2934783老实说,这个错误会导致每行验证完全和你想要的相反*。 – WhozCraig