c ++ читает неопределенное количество строк с помощью eof () - PullRequest
0 голосов
/ 22 октября 2011

У меня проблема с использованием 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 ]

7 голосов
/ 22 октября 2011

Правильный путь:

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++;
}
2 голосов
/ 22 октября 2011
in << name << number;

Это похоже на запись, а не на чтение.Я не прав?

1 голос
/ 22 октября 2011

Это, вероятно, будет более правильным

string name;
int number, n = 0;

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

eof - плохая практика .

Обратите внимание, что здесь есть небольшое отличие от вашего кода: ваш код завершился, когда он обнаружил eof, или зацикливался в течение бесконечного времени, если он обнаружил неправильную строку (например, Hello World), этот код заканчивается, когда он встречается неправильно отформатированный «кортеж» из имени + номера или файл заканчивается (или есть другие ошибки, такие как отключение диска во время операции :-)). Если вы хотите проверить, правильно ли был прочитан файл, после while вы можете проверить, является ли in.eof() истинным. Если это правда, то все файлы были прочитаны правильно.

1 голос
/ 22 октября 2011
int number, n = 0;

Вы не инициализировали n, и, похоже, у вас есть опечатка.

...