如何将字符串和int构成字符串

How to compose a string and an int to a string?

本文关键字:字符串 int      更新时间:2023-10-16

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