为什么在循环条件中使用 iostream::eof 被认为是错误的?
仅仅因为我们还没有到达 EOF,并不意味着接下来读取操作会成功。
考虑你用 C++ 中的文件流读取一个文件。当编写循环以读取文件时,如果你正在检查 stream.eof(),你实际上是在检查文件是否已经到达 eof。
所以你可以像下面这样编写代码 −
示例
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myFile("myfile.txt");
string x;
while(!myFile.eof()) {
myFile >> x;
// Need to check again if x is valid or eof
if(x) {
// Do something with x
}
}
}示例
而当你在循环中直接使用流时,你不需要两次检查条件 −
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myFile("myfile.txt");
string x;
while(myFile >> x) {
// Do something with x
// No checks needed!
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP