两次读取文本文件中的一行 [英] reading a line in text file twice

查看:49
本文介绍了两次读取文本文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文本示例

Ahmed 10
kmal 5
doola 6

我正在使用这段代码来阅读

And I am using this code to read it

if (myfile.is_open())
{
  while ( myfile.good() )
{

    myfile >> name;
    myfile >> phone;
    cout << name <<" "<<phone<<endl;

}
myfile.close();

}

我得到这个输出

Ahmed 10
kmal 5
doola 6
doola 6

为什么此代码两次读取最后一行?

Why does this code read the last line twice ?

推荐答案

尝试

while( myfile >> name >> phone ) {
    // your code here
}

我相信另一种方法的问题是,直到您实际尝试阅读的内容多于预期,才会发出eof信号.也就是说,当您尝试 myfile>>名称在最后一轮.失败了,就像 myfile>>一样.电话,然后您才跳出循环.

I believe the problem with the other approach is that eof isn't signaled until you actually try to read more than you should. That is, when you attempt to myfile >> name on the last round. That fails, as does myfile >> phone and only then do you break out of the loop.

这篇关于两次读取文本文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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