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

169 Views Asked by At

At work we had to replace iostream with a function void output(std::string) :

std::cout << "This is some output." << '\n';

<--Old--
--New-->

output("This is some output");

Of course I have a lot of code where I combine a string and an int, and I already have found one possible solution for this problem:

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());

But I don't really like this solution, as it introduces two additional lines of code and an additional use-once variable. Do you know of any other possible solutions that are more elegant?

2

There are 2 best solutions below

0
On

You can use std::to_string to convert numeric types into std::string, then concatenate them before calling output

output("Some value: " + std::to_string(some_value));
0
On

you can just simply use the std::to_string(value) function and combine two std::string