Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 294
Jan Deinhard Avatar asked Nov 16 '10 13:11

Jan Deinhard


People also ask

How can I compare two strings in C++?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.


1 Answers

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";
like image 88
Armen Tsirunyan Avatar answered Sep 21 '22 15:09

Armen Tsirunyan