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

佐手、 提交于 2019-12-02 05:54:14

"Foo" and "Bar" are literals, they don't have the insertion (<<) operator.

you instead need to use std::string if you want to do basic concatenation:

std::string assemble(int param)
{
    std::string s = "Foo";
    s += doSomething(param); //assumes doSomething returns char* or std::string
    s += "bar";
    return s;
}

Well, you're using C++, so you should be using std::stringstream:

std::string assemble(int param)
{
    std::stringstream ss;
    ss << "Foo" << doSomething(param) << "bar";
    return ss.str();
}; // eo assemble

"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*.

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