简体   繁体   English

在C ++中没有`while(!my_ifstream.eof()){getline(my_ifstream,line)}`

[英]No `while (!my_ifstream.eof()) { getline(my_ifstream, line) }` in C++?

On this website , someone writes: 这个网站上 ,有人写道:

 while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; } 

This is wrong, read carefully the documentation for the eof() memberfunction. 这是错误的,请仔细阅读eof()成员函数的文档。 The correct code is this: 正确的代码是这样的:

 while( getline( myfile, line)) cout << line << endl; 

Why is this? 为什么是这样?

There are two primary reasons. 主要原因有两个。 @Etienne has pointed out one: reading could fail for some reason other than reaching the end of the file, in which case your first version will go into an infinite loop. @Etienne指出了一个问题:除了到达文件末尾之外,读取可能由于某种原因而失败,在这种情况下,您的第一个版本将进入无限循环。

Even with no other failures, however, the first won't work correctly. 但是,即使没有其他故障,第一个也无法正常工作。 eof() won't be set until after an attempt at reading has failed because the end of the file was reached. eof()尝试读取失败才会设置,因为已到达文件末尾。 That means the first loop will execute one extra iteration that you don't really want. 这意味着第一个循环将执行一个您不想要的额外迭代。 In this case, that'll just end up adding an extra blank (empty) line at the end of the file. 在这种情况下,这将最终在文件末尾添加一个额外的空白(空)行。 Depending on what you're working with, that may or may not matter. 取决于您正在使用的内容,这可能或不重要。 Depending on what you're using to read the data, it's also fairly common to see the last line repeated in the output. 根据您用于读取数据的内容,在输出中重复查看最后一行也很常见。

A stream operation (such as reading) can fail for multiple reasons. 流操作(例如读取)可能由于多种原因而失败。 eof() tests just one of them. eof()只测试其中一个。 To test them all, simply use the stream's void * conversion operator. 要测试它们,只需使用stream的void *转换运算符。 That's what's done in the second snippet. 这就是第二个片段中的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM