Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining the last character in a stringstream without copying its whole buffer

If I use this code:

template <typename Streamable>
/* ... */
std::stringstream ss;
ss << function_yielding_a_Streamable();
auto last_char = ss.str().back();

then (I believe) a copy of the string in ss's buffer will need to be created, just for me to get the last character, and it will then be destroyed. Can I do something better instead? Perhaps using the seekp() method?

like image 483
einpoklum Avatar asked Apr 20 '16 12:04

einpoklum


1 Answers

You could do something like this:

char last_char;
std::stringstream ss;
ss << function_yielding_a_Streamable();
ss.seekg(-1,ios::end);//get to the last character in the buffer
ss>>last_char;
like image 160
Biruk Abebe Avatar answered Sep 22 '22 00:09

Biruk Abebe