c ++读取未定义的行数eof() [英] c++ reading undefined number of lines with eof()

查看:151
本文介绍了c ++读取未定义的行数eof()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用eof()处理一个问题。
使用

I'm dealing with a problem using eof(). using

string name;
int number, n=0;
while(!in.eof())
{
    in >> name >> number;
    //part of code that puts into object array
    n++;
}

对我来说听起来很正常,只要文件中没有更多文本。
但是我得到的是n是4200317.当我查看数组条目,我看到第一个ats文件中的那些,其他是0.

sounds normal to me as it whenever there are no more text in the file. But what I get is n being 4200317. When I view the array entries, I see the first ones ats the ones in the file and other being 0s.

什么可能是问题,我该如何解决它?

What could be the problem and how should I solve it? Maybe there's an alternative to this reading problem (having undefined number of lines)

推荐答案

正确的方式:

string name;
int    number;
int    n     = 0;

while(in >> name >> number)
{
    // The loop will only be entered if the name and number are correctly
    // read from the input stream. If either fail then the state of the
    // stream is set to bad and then the while loop will not be entered.

    // This works because the result of the >> operator is the std::istream
    // When an istream is used in a boolean context its is converted into
    // a type that can be used in a boolean context using the isgood() to
    // check its state. If the state is good it will be converted to an objet
    // that can be considered to be true.


    //part of code that puts into object array
    n++;
}

为什么您的代码失败:

string name;
int number, n=0;
while(!in.eof())
{
    // If you are on the last line of the file.
    // This will read the last line. BUT it will not read past
    // the end of file. So it will read the last line leaving no
    // more data but it will NOT set the EOF flag.

    // Thus it will reenter the loop one last time
    // This last time it will fail to read any data and set the EOF flag
    // But you are now in the loop so it will still processes all the
    // commands that happen after this. 
    in >> name >> number;

    // To prevent anything bad.
    // You must check the state of the stream after using it:
    if (!in)
    {
       break;   // or fix as appropriate.
    }

    // Only do work if the read worked correctly.
    n++;
}

这篇关于c ++读取未定义的行数eof()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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