Read a string line by line using c++
I have a std::string
with multiple lines and I need to read it line by line.
Please show me how to do it with a small example.
Ex: I have a string string h;
h will be:
Hello there.
How are you today?
I am fine, thank you.
I need to extract Hello there.
, How are you today?
, and I am fine, thank you.
somehow.
#include <sstream>
#include <iostream>
int main() {
std::istringstream f("line1\nline2\nline3");
std::string line;
while (std::getline(f, line)) {
std::cout << line << std::endl;
}
}
There are several ways to do that.
You can use std::string::find
in a loop for '\n'
characters and substr() between the positions.
You can use std::istringstream
and std::getline( istr, line )
(Probably the easiest)
You can use boost::tokenize
this would help you : http://www.cplusplus.com/reference/iostream/istream/getline/