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

c++ reading undefined number of lines with eof()

本文关键字:未定义 读取 使用 eof c++      更新时间:2023-10-16

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

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

对我来说,这听起来很正常,因为每当文件中没有更多文本时。但我得到的是4200317。当我查看数组条目时,我会看到第一个是文件中的,另一个是0。

可能是什么问题?我应该如何解决?也许有一种替代读取问题的方法(具有未定义的行数(

正确的方法:

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++;
}
in << name << number;

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

int number, n = 0;

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

这可能是更正确的

string name;
int number, n = 0;
while (in >> name && in >> number)
{
    n++;
}

eof是一种糟糕的做法。

请注意,这里与您的代码有一个细微的区别:您的代码在遇到eof时结束,或者如果发现错误的行(例如Hello World(,则无提示循环无限长时间,当遇到名称+编号格式不正确的"元组"或文件结束时(或者存在其他错误,如在操作过程中断开磁盘连接:-(,此代码结束。如果要检查文件是否正确读取,则在while之后,可以检查in.eof()是否为true。如果这是真的,那么所有文件都被正确读取了。