I got a string foo with 2 lines:
string foo = "abc \n def";
How I can read this 2 lines from string foo: first line to string a1 and 2th line to string a2? I need in finish: string a1 = "abc"; string a2 = "def";
I got a string foo with 2 lines:
string foo = "abc \n def";
How I can read this 2 lines from string foo: first line to string a1 and 2th line to string a2? I need in finish: string a1 = "abc"; string a2 = "def";
You could probably read it into a string stream, and from the stream output both words into separate strings.
http://www.cplusplus.com/reference/iostream/stringstream/stringstream/
Use string stream:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string foo = "abc \n def";
std::stringstream foostream(foo);
std::string line1;
std::getline(foostream,line1);
std::string line2;
std::getline(foostream,line2);
std::cout << "L1: " << line1 << "\n"
<< "L2: " << line2 << "\n";
}
Check this link for how to read lines and then split the line into words:
http://stackoverflow.com/questions/1735225/c-print-out-limit-number-of-words/1735549#1735549
This seems like the easiest solution for me, though the stringstream way works too.
See: http://www.sgi.com/tech/stl/find.html
std::string::const_iterator nl = std::find( foo.begin(), foo.end(), '\n' ) ;
std::string line1( foo.begin(), nl ) ;
if ( nl != foo.end() ) ++nl ;
std::string line2( nl, foo.end() ) ;
Then just trim the lines:
std::string trim( std::string const & str ) {
size_t start = str.find_first_of( " " ) ;
if ( start == std::string::npos ) start = 0 ;
size_t end = str.find_last_of( " " ) ;
if ( end == std::string::npos ) end = str.size() ;
return std::string( str.begin()+start, str.begin()+end ) ;
}