9

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?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    Why put the `string` into the `stringstream` in the first place? – Sean Apr 20 '16 at 12:18
  • @Sean: Fair question, see edit. – einpoklum Apr 20 '16 at 12:22
  • Presumably, it doesn't *have* to be a `stringstream`? Perhaps you could use a custom stream instead. – eerorika Apr 20 '16 at 12:26
  • @user2079303: I suppose... but wouldn't that be overkill? – einpoklum Apr 20 '16 at 12:26
  • @einpoklum depends on how big buffer `function_yielding_a_Streamable` generates and whether you need any of it except for the last character. If it generates megabytes of data, I think it would be worth it to store only what you need rather than the entire buffer. – eerorika Apr 20 '16 at 12:30

1 Answers1

9

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;
Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24
  • Wouldn't I then also need to seek back (e.g. if I wrap this in a function taking an ostringstream& which I want to act cleanly)? – einpoklum Apr 21 '16 at 15:12
  • @einpoklum sorry for the late replay, i believe you can do that using *seekp(0)* to seek to to the beginning for insertion. I suppose you meant to say pass *stringstream&* rather than *ostringstream&* since with the latter you can't access the extraction *operator>>* to read the last character. – Biruk Abebe Apr 21 '16 at 17:57