std::ostringstream overwriting initializing string

喜夏-厌秋 提交于 2021-01-29 10:30:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!