首页 > 解决方案 > 解析时忽略txt文件中的某些行

问题描述

我想从 txt 文件中读取文件并将一些行与正则表达式进行比较。txt 文件的第一行应以字符串#FIRST 开头。如果字符串应以“#”开头,则应忽略该行并继续。所以计数器应该有它所做的值 1,它应该转到第二个 if 语句 if(counter==1)。但是它不会进入第二个 if 语句。

txt文件:

#FIRST
#
#haha

我希望代码运行一次后输出会很好\n很好。

输出是:

   good.

它应该是

          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;
  }

标签: c++for-loopgetlinecontinue

解决方案


问题在于break第一if条中的陈述。在获得输入的第一行后,程序遇到该break语句并立即跳出循环。在 for 循环中没有执行进一步的语句,我相信这是您所看到的行为。您将不得不将程序重组为:

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

推荐阅读