0

I want to read files from a txt file and compare some lines with regex. The first line of the txt file should start with the string #FIRST. And if the string should start with a '#' the line should be ignored and it should continue. So counter should have the value 1 which it does and it should go to the second if statement if(counter==1). However it doesn't go to the second if statement.

txt file:

#FIRST
#
#haha

I expect the output to be good\ngood after the code is run once.

The output is:

   good.

And it should be

          good.
          good.

.........

#include <iostream> 
#include <string> 
#include <vector> 
#include <regex> 
#include <fstream> 
#include <sstream>

  int main() {

    std::ifstream input("test.txt");
    std::regex e("#FIRST");
    std::regex b("haha");
    int counter;
    for (counter = 0; !input.eof(); counter++) {
      std::cout << counter << "\n";

      std::string line;
      if (counter == 0) {
        getline(input, line);
        if (std::regex_match(line, e)) {
          std::cout << "good." << std::endl;
          counter++;

        } else
          std::cout << "bad." << std::endl;
        break;
      }

      getline(input, line);
      if (line[0] == '#')
        continue;

      if (counter == 1) {
        getline(input, line);
        if (std::regex_match(line, b)) {
          std::cout << "good." << std::endl;
        } else
          std::cout << "bad." << std::endl;
        break;

      }
    }

    return 0;
  }
senpai
  • 9
  • 4
  • Hi @senpai - can you post the current output? – sanchitarora Mar 26 '19 at 22:04
  • @sanchitarora I have added it to the post at the top – senpai Mar 26 '19 at 22:10
  • Count how may `getline` calls are happening. counter = 0 => 2, counter = 1 => 2 but you only have 3 lines... Simple debug (i.e. printing out the line) would help you find this. – John3136 Mar 26 '19 at 22:15
  • @john I have printed out the lines and I still can't find the problem – senpai Mar 26 '19 at 22:43
  • 1
    Some restructuring of the code would be advisable considering https://stackoverflow.com/questions/4533063/how-does-ifstreams-eof-work – J.R. Mar 26 '19 at 22:49
  • 1
    Expanding on @J.R. 's comment, [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Mar 26 '19 at 23:01

1 Answers1

0

The issue is with the break statement in the first if clause. After getting the first line of the input the program encounters the break statement and breaks out of the loop immediately. No further statements are executed within the for loop which I believe is the behavior you are seeing. You will have to restructure the program to be something like:

for loop {
  getline()
  if (counter == <>) {
    // no break
  } else if (line[0] == '#') {
    continue;
  } else {
    // whatever else you want to get done
  }
}
sanchitarora
  • 822
  • 9
  • 18