基于第一个单词C ++解析文本文件

时间:2014-07-18 17:12:28

标签: c++ parsing text text-files

我试图用C ++编写一个简单的程序,从文本文件中读取信息并将其打印到控制台。文本文件看起来与此类似。

thing1 contents1 
thing2 contents2
thing3 contents3
thing4 contents4

有没有办法可以通过知道前面的单词是contents1来打印thing1控制台?

2 个答案:

答案 0 :(得分:1)

#include <istream>
#include  <string>
#include  <vector>

std::vector<std::string> getContents(std::istream &stream, std::string mark) {
    std::vector<std::string> contents;
    std::string current;

    while(stream) {
        stream >> current;

        if(current == mark) {
            stream >> current;
            contents.push_back(current);
        }
    }

    return contents
}

这是一个非常基本的例子。我不建议使用这个,但它确实完成了工作。它做了什么:如果在流中找到标记,则抓取内容。它没有做什么:大量检查以确保流有效,或者该行是有效的(即内容可能在标记后立即出现)。这也可以在字符串上更容易完成,它只是我个人喜欢使用流

编辑:以为我看到了thing1 = content1。再看一遍,原来是thing1 content1。代码编辑得恰当

答案 1 :(得分:0)

单向,使用std::map

ifstream fin("textfile.txt");

std::string firstw, secondw;

std::map< std::string, std::string> m ;

while ( fin >> firstw >> secondw )
{
   m[firstw] = secondw ;
}

fin.close( );

std::string input_word = "thing1" ; 

// Wrap following in a function, input_word is the search element

if( m.find(input_word) != m.end () )
{
  std::cout << m[input_word] ;
}