How to concatenate a const char array and a char array pointer?

后端 未结 3 1215
梦谈多话
梦谈多话 2021-01-27 04:38

Straight into business: I have code looking roughly like this:

char* assemble(int param)
{
    char* result = \"Foo\" << doSomething(param) << \"bar\         


        
3条回答
  •  生来不讨喜
    2021-01-27 04:59

    "Foo" and "bar" have type char const[4]. From the error message, I gather that the expression doSomething(param) has type char* (which is suspicious—it's really exceptional to have a case where a function can reasonably return a char*). None of these types support <<.

    You're dealing here with C style strings, which don't support concatenation (at least not reasonably). In C++, the concatenation operator on strings is +, not <<, and you need C++ strings for it to work:

    std::string result = std::string( "Foo" ) + doSomething( param ) + "bar";
    

    (Once the first argument is an std::string, implicit conversions will spring into effect to convert the others.)

    But I'd look at that doSomething function. There's something wrong with a function which returns char*.

提交回复
热议问题