[英]How to concatenate a const char array and a char array pointer?
Straight into business: I have code looking roughly like this: 直接从事业务:我的代码大致如下所示:
char* assemble(int param)
{
char* result = "Foo" << doSomething(param) << "bar";
return result;
}
Now what I get is: 现在我得到的是:
error: invalid operands of types ‘const char [4]’ and ‘char*’ to binary ‘operator<<’
Edit: doSomething
returns a char*
. 编辑:
doSomething
返回一个char*
。
So, how do I concatenate these two? 那么,如何将这两个连接起来?
Additional info: 附加信息:
Compiler: g++ 4.4.5 on GNU/Linux 2.6.32-5-amd64 编译器:GNU / Linux 2.6.32-5-amd64上的g ++ 4.4.5
Well, you're using C++, so you should be using std::stringstream
: 好吧,您使用的是C ++,因此您应该使用
std::stringstream
:
std::string assemble(int param)
{
std::stringstream ss;
ss << "Foo" << doSomething(param) << "bar";
return ss.str();
}; // eo assemble
"Foo"
and "Bar"
are literals, they don't have the insertion ( <<
) operator. "Foo"
和"Bar"
是文字,它们没有插入( <<
)运算符。
you instead need to use std::string
if you want to do basic concatenation: 如果要进行基本串联,则需要使用
std::string
:
std::string assemble(int param)
{
std::string s = "Foo";
s += doSomething(param); //assumes doSomething returns char* or std::string
s += "bar";
return s;
}
"Foo"
and "bar"
have type char const[4]
. "Foo"
和"bar"
类型为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*
). 从错误消息中,我收集到表达式
doSomething(param)
类型为char*
(这是可疑的,在某些情况下函数可以合理地返回char*
确实很例外)。 None of these types support <<
. 这些类型都不支持
<<
。
You're dealing here with C style strings, which don't support concatenation (at least not reasonably). 您在这里处理的是C风格的字符串,这些字符串不支持串联(至少不合理)。 In C++, the concatenation operator on strings is
+
, not <<
, and you need C++ strings for it to work: 在C ++中,字符串的串联运算符是
+
,而不是<<
,并且您需要C ++字符串才能起作用:
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.) (一旦第一个参数是
std::string
,则隐式转换将生效以转换其他参数。)
But I'd look at that doSomething
function. 但是我会看一下
doSomething
函数。 There's something wrong with a function which returns char*
. 返回
char*
的函数有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.