How to look at the remaining string 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 you peek the rest of the characters in a string ( "b+c" )? That is, without the next operation starting from the next line?

(An example is contrived, I know.)

+4
source share
4 answers

You can return the string using istream :: seekg () as follows:

 ss.seekg(ss.beg); 

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

+3
source

Try:

 std::getline(ss, s, '='); // gives me "a" std::getline(ss, s); // gives me "b+c" ss.seekg(-(s.size()+1) ,std::ios_base::cur); // Roll back // Need to +1 becuase we throw away a character // with std::getline() that is not in the string. std::getline(ss, s, '+'); // gives me "b" 

The problem with the above is that std :: getline () will throw out "\ n" if it finds it before eof. but if he first finds eof, then we have a problem, since +1 puts us in the wrong place. Thus, it works for the above example, but it will fail for the last line if you cannot guarantee that each line ends with the character '\ n'

So, we can use tellg () if you cannot provide this guarantee:

 std::getline(ss, s, '='); // gives me "a" std::streampos save = ss.tellg(); std::getline(ss, s); // gives me "b+c" ss.seekg(save); // Roll back std::getline(ss, s, '+'); // gives me "b" 
+3
source

You need to either make a new stringstream from s after:

 std::getline(ss, s); // gives me "b+c" std::stringstream ss2(s); std::getline(ss2,s, '+'); // will give b and maintain position in original ss 

Or use the following instead:

 std::getline(ss, s, '+'); // will give b 

Edit: the second option changes the state of ss, so it does not meet your modified criteria.

+1
source

A simple solution to your problem would be to use another std::stringstream for s :

 std::getline(ss, s, '='); // get "a" std::getline(ss, s); std::stringstream ss2(s); // create a stringstream with "b+c" std::getline(ss2, s, '+'); // gets "b" 

Edit: Then, why do you read "b+c" instead of just getting "b" first and then "c" ? (I do not know about your implementation)

+1
source

Source: https://habr.com/ru/post/1481020/


All Articles