解析时忽略 txt 文件中的某些行
Ignoring certain lines in a txt file when parsing
我想从 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
}
}
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 我可以读取静态对象中的文件.txt吗?C++
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 具有文件.txt的 C++ 中的设置
- 如何在 CMakeList 中包含 h/hpp 头文件.txt而不是 cpp 或其他 hpp 文件
- 使用函数读取文件.txt中的矩阵
- 任何人都知道如何解决尝试将从MySQL数据库返回的行打印到文本文件(.txt)中的C++
- 读取文件.txt C
- 为什么我的方法不从文件.txt中读取float类型
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- 读取文件".txt"并将每行的数据分配给循环列表中的新节点C++
- 如何用C++将字符串文件Txt解析成数组
- 如何在c++中读取和编辑文件txt
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 导入文件txt时出错
- 如何仅读取文件.txt中的数字