c ++ 如何阻止我的循环两次吐出最后一个输入
c++ How do I stop my loop from spitting out the last input twice
我正在做一个银行程序,在我的存款函数中,我有以下代码,它从文本文件中读取并将金额存储到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()
几乎总是有问题......
相关文章:
- 在指定的响应之前C++用户输入两次
- 将用户输入验证为整数:用户必须两次输入输入
- C++使用二维数组的程序,该数组要求用户输入两次.它需要将这些输入显示为输出
- 如何修复密码条目,它一次输入两个字符
- 为什么输入文件的最后一行运行两次?
- cin.ignore() 输入两次以获得一次暂停
- 为什么在这里对c++输入文件流进行两次检查
- C 必须将输入输入两次
- 重复上一次输入两次
- C++程序要求我输入两次,即使变量第一次被分配
- c ++ 如何阻止我的循环两次吐出最后一个输入
- 函数读取输入并运行函数两次
- 为什么我必须输入两次
- 如何在获得下一个字符后正确刷新输入缓冲区,而无需按两次回车键!C++
- 为什么 ifstream 返回输入文件的最后一个值两次
- 尝试从输入文件打印,但打印最后一个输入两次
- 为什么我的代码要求"请输入 2-12 之间的数字:"两次?
- 两次读取std::cin的输入
- 如何阻止用户两次输入相同的值
- Boost接受器每次接受两次输入连接,并生成两个线程