将int转换为string并在c ++中添加到existsin字符串

时间:2016-01-28 08:10:37

标签: c++ string

我想知道如何将int转换为字符串然后将其添加到existsin字符串中。即。

std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s

我希望我有道理。非常感谢您提前回答。

2 个答案:

答案 0 :(得分:3)

如果要追加的数字是整数或浮点变量,则使用std::to_string并简单地"添加"它:

int some_number = 123;
std::string some_string = "foo";

some_string += std::to_string(some_number);

std::cout << some_string << '\n';

应输出

foo123

答案 1 :(得分:2)

“现代”方式是使用std::to_string(1)。实际上,对于不同的数字类型存在std::to_string的各种重载。

将这些放在一起你可以写std::string s = "Hello" + std::to_string(1);

或者,您可以使用可以更快的std::stringstream,因为更少的字符串连接操作可能很昂贵:

std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string