解析时忽略 txt 文件中的某些行

Ignoring certain lines in a txt file when parsing

本文关键字:文件 txt      更新时间:2023-10-16

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

txt 文件:

#FIRST
#
#haha

我希望代码运行一次后输出良好。

输出为:

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

问题出在第一个if子句中的break语句上。在获得输入的第一行后,程序遇到break语句并立即脱离循环。在 for 循环中没有执行进一步的语句,我相信这是您看到的行为。您必须将程序重组为:

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