C++ while 循环以从输入文件中读取
C++ while loop to read from input file
我编写了一个函数,该函数使用 while 循环从输入文件中读取事务。不过,我一辈子都无法弄清楚为什么它会两次阅读最后 2 行。使用时
while(InFile){code}
据我了解,它将继续循环,直到文件到达 EOF 标记。我不知道我在这里哪里出错了。
void ProcessTransactions(Bank &acctList, string fileName)
{
Date transDate;
ifstream InFile;
InFile.open(fileName.c_str());
int month;
int day;
int year;
int acctNum;
int transAcctNum;
float amount;
string transType;
while(InFile)
{
InFile >> month >> day >> year;
transDate.SetDate(month, day, year);
InFile >> acctNum;
InFile >> amount;
InFile >> transType;
if(transType == "Transfer")
InFile >> transAcctNum;
cout << amount << endl;
}
}
输入文件
5 1 2012 1212 100.00 Deposit
5 1 2012 2323 100.00 Deposit
5 1 2012 3434 100.00 Deposit
6 1 2012 1212 200.00 Withdrawal
6 1 2012 2323 200.00 Withdrawal
6 1 2012 3434 50.00 Withdrawal
7 1 2012 1212 50.00 Transfer
2323
7 1 2012 2323 80.00 Transfer
3434
7 1 2012 3434 300.00 Transfer
1212
9 1 2012 1212 100.00 Deposit
9 1 2012 2323 100.00 Deposit
9 1 2012 3434 100.00 Deposit
10 1 2012 1212 300.00 Transfer
1212
输出
100
100
100
200
200
50
50
80
300
100
100
100
300
300 //** Why is this output twice ?
提取最后一位数据后,文件标记应已到达 EOF,从而终止循环。
任何帮助将不胜感激!
======================================================================================附加说明/解决方案 : 从: 为什么循环条件中的 iostream::eof 被认为是错误的?
因为iostream::eof只有在读取流的末尾后才会返回true。它并不表示下一次读取将是流的结束。
考虑这一点(并假设下一次读取将在流的末尾)
while(!inStream.eof()){
int data;
// yay, not end of stream yet, now read ...
inStream >> data;
// oh crap, now we read the end and *only* now the eof bit will be
set (as well as the fail bit)
// do stuff with (now uninitialized) data
}
对此:
int data;
while(inStream >> data){
// when we land here, we can be sure that the read was successful.
// if it wasn't, the returned stream from operator>> would be
// converted to false
// and the loop wouldn't even be entered
// do stuff with correctly initialized data (hopefully)
}
提取最后一位数据后,文件标记应该已到达 EOF,从而终止循环。
不。
当您尝试读取超过文件末尾时,将设置 EOF。在这里,您不检查提取是否成功,只检查流是否正常,然后再尝试提取。因此,您将在最后获得额外的迭代。
你应该像这样循环(在Stack Overflow上有很多这样的例子,因为我们不断告诉人们如何做到这一点):
while (InFile >> month >> day >> year)
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量