draw draw - 10 months ago 43
C++ Question

How do you get the remaining string after a string extracted from a sstream variable?

Like I have a

variable contains
"abc gg rrr ff"

When I use >> on that
variable, it gives me
. How can I get the remaining string:
" gg rrr ff"
? It seems neither
does this work.

Answer Source

You can use std::getline to get the rest of the string from the stream:

#include <iostream>
#include <sstream>

using namespace std;

int main() {
        stringstream ss("abc gg rrr ff");
        string s1, s2;
        ss >> s1;
        getline(ss, s2); //get rest of the string!
        cout << s1 << endl;
        cout << s2 << endl;
        return 0;


gg rrr ff

Demo : http://www.ideone.com/R4kfV

There is an overloaded std::getline function in which a third parameter takes a delimiter upto which you can read the string. See the documentation of std::getline: