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

查看:333
本文介绍了在C ++中没有`while(!my_ifstream.eof()){getline(my_ifstream,line)}`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此网站上,有人写:



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


这是错误的,请仔细阅读文档为eof()
成员函数。正确的代码是:

This is wrong, read carefully the documentation for the eof() memberfunction. The correct code is this:

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


为什么?

推荐答案

有两个主要原因。 @Etienne指出:除非达到文件结尾,否则读取可能失败,在这种情况下,您的第一个版本将进入无限循环。

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.

即使没有其他失败,但是,第一个将无法正常工作。 之后,在之前, 将不会设置 ,因为到达文件末尾。这意味着第一个循环将执行一个你不想真正想要的额外的迭代。在这种情况下,这将最终在文件的末尾添加一个额外的空白(空)行。根据你的工作,这可能或可能不重要。根据您用于读取数据的内容,看到输出中重复的最后一行也很常见。

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. 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.

这篇关于在C ++中没有`while(!my_ifstream.eof()){getline(my_ifstream,line)}`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆