Goodnight.

There is a piece of code that reads lines from a file:

while((i<num) && (!fin.eof())) { //что-то //после каждой считанной строки из файла выводится выводится строка в консоль. } 

And there is a file with such content (the file ends at the end of line 5, there are no more characters):

 1 hello helo 0 0 2 hello helo 2 4 3 hello helo 4 8 4 hello helo 6 12 5 hello helo 8 16 

When num = 5, it reads correctly all 5 lines, if n = 6 and more, then something else is read and outputs 1 line more. It seems that eof finds the end of the file not at the end of line 5, but at the beginning of 6 O_o. What could be the error?

A string is written to the file with << endl; at the end.

  • @Cookie, endl, as far as I understand, is a newline character, from there you get the sixth one. - etki
  • @Cookie, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina

2 answers 2

@Cookie , unfortunately, in the code fragment in your question you omitted the actual reading from the file.

Most likely, after reading the line (say, getline(fin, str) ) you do not check whether you really read the str , and output its contents, but the end of the file is actually detected during the read operation, and not at all by the fin.eof() method which only checks the previously installed end-of-file flag.

You can correctly read N lines, for example, like this:

  while (i < num && getline(fin, str)) { i++; cout << str << endl; ... } 
     #include <iostream> #include <fstream> int main() { std::ifstream fin; fin.open("test1.txt"); if( !fin.is_open() ) { std::cout << "\nError opening file."; return 1; } int i = 0; int num = 6; char Buffer[256]; do { if( fin.getline(Buffer, 80) ) { std::cout << Buffer << "\n"; ++i; } else break; } while( i < num ); fin.close(); return 0; } 
    • The given code does not correspond to the question at all. Here you write to a file, and the question was about reading from a file. - aleks.andr
    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky
    • I explained deployed, most likely, some people do not see the obvious. This program shows how to get the contents of a text file using two conditions, the first is a check on reception, if the line is empty, the cycle ends, the second condition is the indicator of the number of reception lines, the counter is full, the program ends. - jnz