C++:如何用STL逐行遍历std :: string中的文本?

Jan*_*ard 17 c++ string boost iterator stl

我在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;
}
Run Code Online (Sandbox Code Playgroud)

我以为我已经尝试过了.我收到了一个编译错误并把它丢了.快点!

Arm*_*yan 17

为什么要将文本保留在源文件中?将其保存在单独的文本文件中.用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 
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

std::string text = 
   "Line 1 contents\n"
   "Line 2 contents\n"
   "Line 3 contents\n";
Run Code Online (Sandbox Code Playgroud)

  • 如果你真的需要使用`std :: string`,你可以将它包装在`std :: stringstream`中并应用Armen的解决方案. (5认同)

Fre*_*Foo 8

使用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;
Run Code Online (Sandbox Code Playgroud)

版画

foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

请注意,它会跳过空行,这可能是您想要的,也可能不是.