5

For example, the stringstream contains "abc\n", I want to remove the last char '\n'.

I know it can be done by using 'str' first.

But could it be done without stringstream::str()?

user1633272
  • 2,007
  • 5
  • 25
  • 48
  • 3
    related: https://stackoverflow.com/questions/4546021/remove-char-from-stringstream-and-append-some-data. However, most answers there suggest to use `str`. Imho the best solution is not to insert the last char into the stream in the first place – 463035818_is_not_an_ai Jun 29 '17 at 09:59

2 Answers2

2

No, there isn't, at least not in a guaranteed manner. Although internally, it maintains a string buffer, you currently do not have access to it without a copy being made. There is a proposal to change this:

Streams have been the oldest part of the C++ standard library and their specification doesn’t take into account many things introduced since C++11. One of the oversights is that there is no non-copying access to the internal buffer of a basic_stringbuf which makes at least the obtaining of the output results from an ostringstream inefficient, because a copy is always made. I personally speculate that this was also the reason why basic_strbuf took so long to get deprecated with its char * access. With move semantics and basic_string_view there is no longer a reason to keep this pessimissation alive on basic_stringbuf.

Internally, there is no reason why there should be this limited, as I believe (I may be wrong) that basic_stringbuf requires a basic_string buffer, and Clang certainly implements basic_stringbuf in such a manner.

Right now, you can stringstream like any other stream, or access a copy of it's underlying buffer, however, you cannot modify the buffer directly. This means that any attempts to modify the end of the stream require copying the underlying buffer or reading bytes until the end.

Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67
2
 stringstream ss;
 ss<<"abc\n";
 ss.seekp(-1, std::ios_base::end);
 ss << '\0';
Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 5
    That does not remove the character. It replaces the character with a different character. And recall that C++ strings and stringstreams are not null-terminated (or, at least, nulls do not uniquely represent termination; they may be used elsewhere) so this isn't even a valid imitation of removing the character. – Lightness Races in Orbit May 13 '19 at 03:23
  • 1
    It may not work in all circumstances, depending on what the result is used for, but for (at least) just printing out the resulting string value it works fine. – Maxim Paperno Jun 16 '22 at 02:54