【问题标题】:Parsing a text file based on first word C++基于第一个单词 C++ 解析文本文件
【发布时间】:2014-07-18 17:12:28
【问题描述】:

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

thing1 contents1 
thing2 contents2
thing3 contents3
thing4 contents4

知道前面的单词是thing1,我可以打印contents1控制台吗?

【问题讨论】:

  • 是的,有办法。
  • 您想调用带有参数thing1 的类型“函数”并带来相关值(如果contents1)?
  • 你会考虑使用像 perl 这样的语言来代替吗?在为文件和字符串操作而设计的语言中,这将非常容易。
  • 我认为 perl 是为正则表达式设计的?
  • 你的具体目标是什么,根据事物列中指定的内容,对内容列数据做一些事情?

标签: c++ parsing text text-files


【解决方案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。代码编辑得当

【讨论】:

  • 有什么你建议使用的吗,我对 C++ 相当熟悉,所以如果需要,它是半复杂的。
  • 也许只对字符串进行操作?尽管 istream 仍然是安全的,因为它是 stl 流和大多数自定义流实现的基本类型。如果您确实使用流,请检查比我做的更多。例如,我们的程序假设每件事都有一个内容。但如果没有呢?我们的流不知道这一点,并会尝试从无到有。也许使用比矢量更小的东西(如果有更小的东西,idk)
  • 对于这个程序,每个thing 都会有一个content,因为这个程序写入一个文件,然后用户可以选择读回数据。
【解决方案2】:

一种方式,使用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] ;
}

【讨论】:

  • 为什么不只是 std::cout
  • @DTSCode 因为如果input_word 不存在于地图中,[] 重载运算符将添加该输入地图。
  • 但它不会只是“”吗?
  • @DTSCode 是的,但想法是从地图中检索,而不仅仅是添加未找到的新单词。在其他部分中,第一部分可以处理这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 2013-08-14
  • 1970-01-01
  • 2013-12-25
相关资源
最近更新 更多