c++ - 使getline检查输入文件的第二行和第三行
问题描述
我已经检查了有关此主题的大多数 stackoverflow 问题,但我似乎没有得到正确的答案。
我正在从 txt 文件中读取字符串,然后使用正则表达式检查 txt 文件的每一行是否具有正确的字符串。
如果输入文件的第一行不是“#FIRST”,我的代码会检查输入文件的第一行并打印出“bad”。我正在尝试对接下来的两行做同样的事情,但是我不知道如何告诉 getline 在第一行正常后只检查第二行。
第二行应该是“这是一条评论”。第三行应该是“#SECOND”。
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <fstream>
#include <sstream>
int main (){
std::ifstream input( "test.txt" );
for( std::string line; getline( input, line ); )
{ std::regex e("#FIRST");
std::regex b("#this is a comment");
//std::regex c("#SECOND");
if(std::regex_match(line,e))
std::cout << "good." << std::endl;
else
std::cout << "bad." << std::endl;
if(std::regex_match(line,b))
std::cout << "good." << std::endl;
else
std::cout << "bad." << std::endl;
break;
}
return 0;
}
输入文件
#FIRST
#this is a comment
#SECOND
解决方案
一种解决方案是存储您要进行的检查的列表,然后遍历它们。对于每个检查,读取一行并查看它是否匹配:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> validLines {
"#FIRST",
"this is a comment",
"#SECOND"
};
std::istringstream fileStream { // pretend it's a file!
"#FIRST\n" \
"this is a comment\n" \
"this line should fail\n"};
std::string fileLine;
for (auto const& validLine : validLines) {
// for every validity check, read a line from the file and check it
if (!std::getline(fileStream, fileLine)) {
std::cerr << "Failed to read from file!\n";
return 1;
}
if (validLine == fileLine) { // could be a regex check
std::cout << "good\n";
}
else {
std::cout << "bad\n";
}
}
}
这只会读取您检查过的行。如果文件中有更多行,则根本不会读取它们。
另请注意,我做了一些简化,使用字符串而不是文件,并使用简单匹配而不是正则表达式,但这对您关心的位没有任何影响。
只是为了好玩,如果您只需要检查某些行号,这是另一种方法:
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
int main()
{
using LineCheckMap = std::unordered_map<std::size_t, std::string>;
LineCheckMap validLines {
{3, "#SECOND"}
};
std::istringstream fileStream { // pretend it's a file!
"#FIRST\n" \
"this is a comment\n" \
"this line should fail\n"};
std::string fileLine;
std::size_t lineCount {0};
while (std::getline(fileStream, fileLine)) {
// for every line in the file, add to a counter and check
// if there is a rule for that line
++lineCount;
LineCheckMap::const_iterator checkIter = validLines.find(lineCount);
if (std::end(validLines) != checkIter) {
if (checkIter->second == fileLine) {
std::cout << "good\n";
}
else {
std::cout << "bad\n";
}
}
}
}
推荐阅读
- python - 使用 df.applymap(str) 时如何忽略 NAN 转为字符串
- .net - 未捕获的 Sys.InvalidOperationException:Sys.InvalidOperationException:“CaptionText”不是属性或现有字段
- arrays - 如何以数组的形式读取单行上的数字列表?
- spring-integration-sftp - Spring Integration Sftp - 如何初始化出站适配器以发送文件
- go - 当第二个结构使用字段子集时,将结构列表转换为另一个结构的列表
- opencv - OpenCV 4.5.3 中的 OpenCV cv::ORB::ScoreType 错误
- javascript - Promise的executor内部操作的含义是异步的
- scala - Akka HTTPS 如何支持 TLS1.2
- java - 从 Word 中的自动增量单元格获取值
- python - 分类任务的 Xgboost 自定义损失函数