问题
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...
回答1:
@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";
来源:https://stackoverflow.com/questions/62238203/stdostringstream-overwriting-initializing-string