Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

Like I have a stringstream variable contains "abc gg rrr ff"

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

like image 883
draw Avatar asked Jun 08 '11 23:06

draw


People also ask

How do I get the rest of a line in C++?

Keep using operator>> , it will extract the rest of it in whitespace-delimited pieces.

How do you clear a Stringstream variable?

For clearing the contents of a stringstream , using: m. str("");

Can you return a Stringstream?

You can't return a stream from a function by value, because that implies you'd have to copy the stream.

Is Stringstream a string?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.


2 Answers

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

Output:

abc 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:

  • std::getline
like image 81
Nawaz Avatar answered Sep 22 '22 19:09

Nawaz


#include <iostream> #include <sstream> #include <string> using namespace std;  int main() {     string str("123 abc");     int a;     istringstream is(str);     is >> a;      // here we extract a copy of the "remainder"     string rem(is.str().substr(is.tellg()));      cout << "Remaining: [" << rem << "]\n"; } 
like image 24
Jnana Avatar answered Sep 22 '22 19:09

Jnana