Jan Deinhard
Jan Deinhard

Reputation: 20205

C++: How to iterate over a text in a std::string line by line with STL?

I have a text in a std::string object. The text consists of several lines. I want to iterate over the text line by line using STL (or Boost). All solutions I come up with seem to be far from elegant. My best approach is to split the text at the line breaks. Is there a more elegant solution?

UPDATE: This is what I was looking for:

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

Upvotes: 21

Views: 16842

Answers (3)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

Why do you keep the text in your source file? Keep it in a separate text file. Open it with std::ifstream and iterate over it with 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 
   }
}

Alternatively, if the text HAS to be in a std::string variable read line by line using std::istringstream in a similar manner

If your question is how to put the text lexially into your code without using +, please note that adjacent string literals are concatenated before compilation, so you could do this:

std::string text = 
   "Line 1 contents\n"
   "Line 2 contents\n"
   "Line 3 contents\n";

Upvotes: 18

Fred Foo
Fred Foo

Reputation: 363807

Use 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;

prints

foo
bar
baz

Note that it skips over empty lines, which may or may not be what you want.

Upvotes: 10

KevenK
KevenK

Reputation: 3021

If you want to loop line by line, as you say, why would splitting the text at line breaks not be exactly what you want?

You didn't post code showing how you're doing it, but your approach seems correct to accomplish what you said you wanted. Why does it feel inferior?

Upvotes: 3

Related Questions