Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ostringstream overwriting initializing string

The following code results in "0004567" on clang++-7

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    ostringstream oss{"1234567"};
    oss << "000";
    cout << oss.str() << endl;
}

Now is this correct STL implementation?

I can't think of how is it useful to initialize with a string that will be overwritten...

like image 524
gatopeich Avatar asked Mar 19 '26 13:03

gatopeich


1 Answers

@IgorTandetnik gave your a solution - to add std::ios_base::app std::ostringstream constructor argument.

However, there is no benefit in passing the initial string (and only a string) into constructor. The argument still gets copied, similar to what oss << "1234567"; does, but it requires providing an extra constructor argument which risks introducing a programming error (and it does in your code).

I suggest keeping it simple:

ostringstream oss;
oss << "1234567";
oss << "000";
// alternatively, just do oss << "1234567000";
like image 199
Maxim Egorushkin Avatar answered Mar 22 '26 02:03

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!