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()?
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()?
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.
stringstream ss;
ss<<"abc\n";
ss.seekp(-1, std::ios_base::end);
ss << '\0';