如何将字符串和int构成字符串
How to compose a string and an int to a string?
在工作中,我们必须用函数 void output(std::string)
替换iostream:
std::cout << "This is some output." << 'n';
<--Old--
--New-->
output("This is some output");
当然,我有很多代码,其中我结合了一个字符串和一个int,我已经找到了一个解决此问题的解决方案:
int some_value = 5
std::cout << "Some value: " << some_value << 'n';
<--Old--
--New-->
int some_value = 5;
std::stringstream tmp_stream;
tmp_stream << "Some value: " << some_value << 'n';
output(tmp_stream.str());
,但我真的不喜欢这种解决方案,因为它引入了另外两行代码和一个额外的使用变量。您知道还有其他更优雅的解决方案吗?
您可以使用 std::to_string
将数字类型转换为 std::string
,然后在调用 output
output("Some value: " + std::to_string(some_value));
您只需使用std :: to_string(value)函数,然后组合两个std :: string
相关文章:
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 构造<int>具有 2 个字符串文字的向量
- 字符串中int的加法运算
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- cin >> int 给定一个字符串将 int 赋值为 0
- 将字符串中的 int 转换为字母;
- 使用 switch,但我想用字符串而不是 int 进行选择
- 两个数组,int 和 string,如何显示带有对应 int 的字符串?
- 从字符串流中读取具有特定字段宽度的 int
- win 表单应用程序字符串^ 到 int
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 将字符串转换为 int 后的随机值
- 如何检查字符串是否正确以将其转换为 int?
- 在 c++ 中逐个字符从字符串传递到 int 时不精确
- <int> 使用 fmt 库将向量转换为字符串
- 我正在尝试将 int 值插入字符串,而不是 1,我得到 10
- 为什么编译:字符串 = int
- C++ 隐式类型转换字符串 -> int?
- 如何在C++中连接字符串+int+字符串