0

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.

  • I think you should add `break;` to line number 231 and remove lines 67-82 entirely. If you encounter any errors, please post a [mcve]. – Quimby Aug 03 '22 at 13:03
  • you have to add detail to this question, post the code you are using and describe where the code fails. – Stack Danny Aug 03 '22 at 13:03
  • 1
    You asked how to modify "the code" but you have not shown any code. From what I can tell, your actual format is "number of lines in matrix" followed by blank line, followed by the number of lines given in that first line. So if you read the first line and it does not contain a single value, or if input terminates early for any of the subsequent lines in that record, it's obviously an error. – paddy Aug 03 '22 at 13:04
  • Maybe structure your file reading code like this example code: [https://stackoverflow.com/questions/55977686/how-to-read-text-file-lines-into-vectors](https://stackoverflow.com/questions/55977686/how-to-read-text-file-lines-into-vectors) – drescherjm Aug 03 '22 at 14:15

1 Answers1

0

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;
}
Scott
  • 60
  • 6