使getline检查输入文件的第二行和第三行

问题描述 投票:1回答:1

我已经检查了关于这个主题的大多数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
c++ regex ifstream getline
1个回答
0
投票

一种解决方案是存储您要进行的检查列表,然后循环遍历它们。对于每个检查,请阅读一行,看看它是否匹配:

#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";
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.