const char* concatenation

前端 未结 12 2169
抹茶落季
抹茶落季 2020-11-29 18:09

I need to concatenate two const chars like these:

const char *one = \"Hello \";
const char *two = \"World\";

How might I go about doing tha

12条回答
  •  情深已故
    2020-11-29 18:40

    You can use strstream. It's formally deprecated, but it's still a great tool if you need to work with C strings, i think.

    char result[100]; // max size 100
    std::ostrstream s(result, sizeof result - 1);
    
    s << one << two << std::ends;
    result[99] = '\0';
    

    This will write one and then two into the stream, and append a terminating \0 using std::ends. In case both strings could end up writing exactly 99 characters - so no space would be left writing \0 - we write one manually at the last position.

提交回复
热议问题