Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to peek at the remaining stringstream characters after using getline?

std::string s;
std::stringstream ss;
ss << "a=b+c" << std::endl << "d=e+f";

std::getline(ss, s, '=');   // gives me "a"
std::getline(ss, s);        /* gives me "b+c"  <- just want to peek: don't
                                                  want to change state of ss */
std::getline(ss, s, '+');   // BUT still want "b" here, not "d=e"

s now contains "a" Now, how do I peek at the remaining characters of the line ("b+c")? That is, without causing the next operation to start at the next line?

(Example contrived, I know.)

like image 995
mchen Avatar asked Feb 17 '23 13:02

mchen


1 Answers

You can revert the stringstream using istream::seekg() like this:

ss.seekg(ss.beg);

Then you can read it all over again. This is better than creating a new one, as it saves memory, and is a tiny bit faster.

like image 105
Anickyan Avatar answered Apr 27 '23 02:04

Anickyan