c ++:解析文件以找到精确的行

时间:2014-01-25 12:43:03

标签: c++ parsing

我是初学者我是c ++所以我不知道像我搜索这样的函数是否已经存在。我想要一个解析文件的函数,找到一个以精确字符串开头的行,并返回它。

例如,如果我有这样的文件:

test  4645
foo   erf   rfr 564
bar   I like train
sponge bob

我想做点什么

std::string line = Func("/my/path/file", "bar");
std::cout << line << std::endl; // display bar    I like train 

3 个答案:

答案 0 :(得分:0)

该函数不存在,但所有构建块都已在C ++标准库中准备就绪。像

这样的东西
std::string Func(const std::string& file, const std::string& prefix)
{
    std::ifstream input(file);
    std::string line;
    while (std::getline(input, line))
        if (line.find(prefix) == 0)
            return line;
    return "";
}

答案 1 :(得分:0)

在每行中解析前缀的流:

#include <iostream>
#include <sstream>

int main() {
    std::istringstream in(
        "test  4645\n"
        "foo   erf   rfr 564\n"
        "bar   I like train\n"
        "sponge bob\n");

    std::string prefix = "bar";

    std::string line;
    while(std::getline(in, line)) {
        if(line.compare(0, prefix.size(), prefix) == 0) {
            std::cout << "Result: " <<  line << '\n';
            return 0;
        }
    }
    std::cout << "No result\n";
    return -1;
}

答案 2 :(得分:-2)

你应该逐行阅读文件,试着在行中找到特定的单词 试试这个

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string find_in_line (const string& fileName, const string& searchWord)
{
string STRING;
ifstream infile;
infile.open (fileName);

while(!infile.eof()) // To get you all the lines.
{
    getline(infile,STRING); // Saves the line in STRING.
    if (STRING.find(searchWord) != std::string::npos){        
    {
        // YOU GOT THE LINE CONTAINING "bar"
        infile.close();            
        return STRING;
    }

}
infile.close();
}

我认为这应该有用......