Frage

I am working on a FileReader function which does a specific function depending on the line.

However the last line of the file I want to read is always blank for some reason, and that messes up my program.

Is there a way I can tell the program to stop at that point?

When trying to run it, I get the following output

Starting program: terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr - - 1 1 Abort

And I know it is because of that blank line since I told the program to get specific elements on each line and those elements are null on that line.

War es hilfreich?

Lösung

From what I understand, you have something like this:

std::ifstream file("file.txt");
std::string line;
while(getline(file,line)) {
  //read the line
}

I also gather (correct me if I'm wrong) that at the end of your file, you have TWO newlines, like this:

line1\nline2\n\n

If this is the case, the while loop body will for sure be executed on one empty line at the end. To get around this, just ignore the empty line:

while(getline(file,line)) {
  if (line == "") continue;
  //read the line
}

If this doesn't work, it's because I misunderstood your question, and in this case please provide some more details.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top