c ++用eof()读取未定义的行数

时间:2011-10-22 08:27:28

标签: c++ eof

我正在处理使用eof()的问题。 使用

string name;
int number, n=0;
while(!in.eof())
{
    in >> name >> number;
    //part of code that puts into object array
    n++;
}
只要文件中没有更多文字,

听起来就像我一样。 但我得到的是n为4200317.当我查看数组条目时,我看到第一个是文件中的那些,其他是0。

可能是什么问题,我该如何解决?也许有一个替代这个阅读问题(有不确定的行数)

4 个答案:

答案 0 :(得分:7)

正确的方法:

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++;
}

答案 1 :(得分:2)

in << name << number;

这看起来像写作,而不是阅读。 我错了吗?

答案 2 :(得分:1)

int number, n = 0;

您没有初始化n,而且您似乎有拼写错误。

答案 3 :(得分:1)

这可能更正确

string name;
int number, n = 0;

while (in >> name && in >> number)
{
    n++;
}

eof is a bad practice

请注意,这里与您的代码存在细微差别:代码在遇到eof时会结束,或者如果找到错误的行(例如Hello World),则会无限循环无限时间,这个当代码遇到名称+数字的非正确格式化的“元组”或文件结束时(或者存在其他错误,例如在操作期间断开磁盘:-)),代码结束。如果要检查文件是否已正确读取,请在while之后检查in.eof()是否为真。如果是,那么所有文件都被正确读取。