首先你需要将整数转换为字符串。 这可以使用sprintf()
,itoa()
或stringstream
与运营商<<
的第二件事是要了解+
做什么操作来完成。
"This is a message for: " + temp + num1 + " " + temp + num 2;
首先将采取前两个参数"This is a message for: " + temp
。第一个参数被认为是一个以空字符结尾的字符串,第二个参数是一个整数。这种操作没有预定义的操作符+
。所以现在不需要进行总结,我们已经无法编译。
我可以提出两个解决方案:
int num1 = 10;
int num2 = 5;
char buf[64];
string temp = "Client";
sprintf(buf, "This is a message for: %s%d %s%d", temp.c_str(), num1, temp.c_str(), num2);
// Dangerous, can walk out of allocated memmory on the stack,
// which may not throw an exception in runtime but will mess the memory
而且更安全
#include <sstream>
int num1 = 10;
int num2 = 5;
string temp = "Client";
stringstream ss;
ss << "This is a message for: " << temp << num1 << " " << temp << num2;
ss.str().c_str(); // Message is here
什么语言是这个吗? –
取决于您未指定的语言。 –
我的错误是语言是C++。编辑的主帖添加此。 –