在 c++ 中将 int 转换为字符串并添加到 existin 字符串
Converting int to string and adding to an existin string in c++
我想知道如何将 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
相关文章:
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 连接资源文件中的字符串,并将其传递给菜单项字符串 (winapi) c++
- 拆分字符串输入并查找字符是否有效
- 二进制字符数组转换为字符串流并从缓冲区弹出
- 文本文件中的 grep 字符串,并将它们复制到 CMake 中的目录中
- C++最快的字符串小写并查找
- 从文件到字符串读取并传递到功能
- 如何在其中创建2D字符串向量并插入数据
- 输入到字符串流并在单个语句中转换为字符串.可以没有帮助程序类
- 如何查找查看一个字符串是否位于另一个字符串内部并替换它
- std::variant 存储多个字符串类型并区分它们
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 将char添加到字符串中并删除char数组
- 如何将浮子值的字节存储在字符串中并以后检索值
- 如何存储在字符串中并转换为字符数组
- 如何记录QObject::tr的原始字符串,并仍然向GUI显示翻译
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果
- 将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白
- 将浮点数转换为字符串,并指定精度和十进制数字数?