代码之家  ›  专栏  ›  技术社区  ›  Jan Deinhard

C++:如何在STL中逐行遍历文本中的一个文本?

  •  17
  • Jan Deinhard  · 技术社区  · 15 年前

    我在std::string对象中有一个文本。正文由几行组成。我想使用STL(或Boost)逐行遍历文本。我提出的所有解决方案似乎都很不优雅。我最好的方法是在换行处拆分文本。有更优雅的解决方案吗?

    更新:这就是我要找的:

    std::string input;
    // get input ...
    std::istringstream stream(input);
    std::string line;
    while (std::getline(stream, line)) {
      std::cout << line << std::endl;
    }
    

    我想我已经试过了。我发现了一个编译器错误,就把它扔掉了。快点!

    3 回复  |  直到 13 年前
        1
  •  17
  •   giuspen    13 年前

    为什么要将文本保存在源文件中?将其保存在单独的文本文件中。用std::ifstream打开它并用 while(getline(...))

    #include <iostream>
    #include <fstream>
    
    int main()
    {
       std::ifstream  fin("MyText.txt");
       std::string    file_line;
       while(std::getline(fin, file_line))
       {
          //current line of text is in file_line, not including the \n 
       }
    }
    

    或者,如果文本必须在 std::string 变量逐行读取使用 std::istringstream 以类似的方式

    如果您的问题是如何在不使用+的情况下将文本词素放入代码中,请注意在编译之前相邻的字符串文字是串联的,因此您可以这样做:

    std::string text = 
       "Line 1 contents\n"
       "Line 2 contents\n"
       "Line 3 contents\n";
    
        2
  •  8
  •   Fred Foo    15 年前

    使用 Boost.Tokenizer :

    std::string text("foo\n\nbar\nbaz");
    
    typedef boost::tokenizer<boost::char_separator<char> > line_tokenizer;
    line_tokenizer tok(text, boost::char_separator<char>("\n\r"));
    
    for (line_tokenizer::const_iterator i = tok.begin(), end = tok.end();
         i != end ; ++i)
        std::cout << *i << std::endl;
    

    印刷品

    foo
    bar
    baz
    

    注意,它跳过空行,空行可能是您想要的,也可能不是您想要的。

        3
  •  3
  •   KevenK    15 年前

    如果你想循环 line by line ,正如您所说,为什么在换行符处拆分文本并不是您想要的那样?

    你没有发布代码来说明你是如何做到的,但是你的方法似乎是正确的,可以实现你所说的你想要的。为什么会觉得自卑?