为什么循环条件内的 iostream::eof 被认为是错误的?
在循环中使用 iostream::eof 被认为是错误的,因为我们还没有到达 EOF。因此,它并不意味着下一次读取会顺利进行。
当我们想要使用 C++ 中的文件流读取文件时,当我们在循环中使用循环在文件中写入时,如果我们使用 stream.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