Wednesday26
Wednesday26

Reputation: 1

C++ How to read two lines from string to separate strings?

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

Upvotes: 0

Views: 2671

Answers (3)

Eld
Eld

Reputation: 984

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 ) ;
}

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264739

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:
C++ print out limit number of words

Upvotes: 8

just_wes
just_wes

Reputation: 1318

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/

Upvotes: 1

Related Questions