Home > Software design >  How to abort when the number of rows in the file is less than the number of rows read in the target
How to abort when the number of rows in the file is less than the number of rows read in the target

Time:08-06

Now I have a txt file like this:

5

1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
5

1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
...

One loop of this file is 7 lines, and the second line of the 7 lines is a blank line. My file has a total of 5 loops , but when my code is set to read 10 loops, the code will not report an error, how should I modify the code to report an error at the end of the file, pay attention to my text file a blank line appears.

#include<fstream>
#include<string>
int main()
{

  std::ifstream get_in("tst.txt", std::ios :: in );

  for ( int loop=0;loop<10;loop   )
  {
    std::string line;

    for ( int i=0;i<7;i   )
    {
      getline(get_in, line);
    }
  }
return 0;
}

This is a simplified example of my code, I want it to error out when the text is not enough for the number of rows I want to read, instead of running normally.

CodePudding user response:

Check the input stream's eof bit, which can be done by directly accessing it get_in.eofbit or by using the eof() function, get_in.eof().

I would recommend using the eof() function.

I am not sure what you are doing with your code, but here is a simple to understand modification of your code as a demonstration:

#include <fstream>
#include <string>
#include <iostream>

int main()
{

  std::ifstream get_in("tst.txt", std::ios :: in );
  std::string line;
  for ( int loop=0;loop<10;loop   )
  {
    if(get_in.eof()) { std::cout << "EOF"; break; }
    for ( int i=0;i<7;i   )
    {
      std::getline(get_in, line);
      if(get_in.eof()) break;
      std::cout << line << std::endl;
    }
  }
return 0;
}
  • Related