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

Converting int to string and adding to an existin string in c++

本文关键字:字符串 串并 添加 existin 字符 c++ 中将 int 转换      更新时间:2023-10-16

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

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

我希望我说得有道理。非常感谢您的任何答案。

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

int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << 'n';

应该输出

福123

"现代"的方式是使用 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
相关文章: