cpp传递带变量的字符串来起作用

时间:2015-01-27 22:07:15

标签: c++ string char

我正在尝试将字符串传递给接受std::string的函数。但我希望字符串包含三个变量,一个char和两个整数。 我无法让它工作我目前有(例子):

myFunction("the char is: " + std::string(&charVar) + ", int1: " + std::to_string(x1) + ", int2: " + std::to_string(x2) + " and that's it!");

当我打印字符串时,我得到以下内容:

"the char is: U\377\377\377\377, int1: 45, int2: 6 and that's it!"

其中charVar ='U',int1 = 45且int2 = 6.

所以问题是U之后的/ 377是什么,主要是有更好的方法来做到这一点。谢谢!

1 个答案:

答案 0 :(得分:2)

使用std::ostringstream

#include <sstream>
//...
std::ostringstream strm;
strm << "the char is: " << charVar << ", int1: " << 
     x1 << ", int2: " << x2 <<  " and that's it!";
myFunction(strm.str());