为什么在循环条件里使用 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!
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP