c++ - 如何将一个字符串和一个int组合成一个字符串?

标签 c++ string c++11 iostream

<分区>

在工作中,我们必须用函数 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));

关于c++ - 如何将一个字符串和一个int组合成一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41222851/

相关文章:

c++ - 如何将 std::string 复制到 std::vector<char> 中?

c++ - 了解 C++11 中 std::function 的模板参数?

c++ - 为什么我不能添加一个带有类型查找的抽象层来剥离 C++ 中的引用?

c++ - 使用 WinSock2 开发,CreateThread() 函数出错

c# - 在 C++ 中使用 C# dll 时出现 C2380 错误

C++ 编译器忽略具有模板化类型的类特化

python - 如何从aiohttp中的url获取查询字符串参数?

c++ - 将R,G,B阵列转换为RGB阵列

python - 使用 re.sub 替换不同大小的小数时对齐小数位

c++ - 如何让成员函数实现依赖于类的模板参数?