c++ - 解析时忽略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;
}
解决方案
问题在于break
第一if
条中的陈述。在获得输入的第一行后,程序遇到该break
语句并立即跳出循环。在 for 循环中没有执行进一步的语句,我相信这是您所看到的行为。您将不得不将程序重组为:
for loop {
getline()
if (counter == <>) {
// no break
} else if (line[0] == '#') {
continue;
} else {
// whatever else you want to get done
}
}
推荐阅读
- python - 将具有相同列值的 DataFrame 行加在一起,但保留顺序
- python - 负维度和模块keras.backend没有属性常见错误
- python - scipy中密集线性方程组的稀疏解
- mysql - MySQL 统一列
- html - 将等高数字的圆圈添加到药丸文本的左侧
- python - 我们如何使用 python 正则表达式解析文本?
- javascript - 如果具有相同的 id,则添加具有相同值的属性
- reactjs - 基于任何字符实时搜索外部数据 - React Hooks
- javascript - 如何将 2D Javascript 数组传递给 wasm 函数?
- c - 正确分配内存和释放?