0

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?

johannesmik
  • 731
  • 1
  • 8
  • 18
  • Bother. I was in the process of suggesting the OP wrote an `output_stream` class, which sent the output to the function `output`. Either by doing it properly via a streambuf, or just by writing a class which had a bunch of `operator <<`. That way they just need to change `std::cout` to `g_output`. Can't write that answer because the question has been closed as duplicate. – Martin Bonner supports Monica Dec 19 '16 at 12:50
  • Thank you for the response! – johannesmik Dec 19 '16 at 12:55
  • @johannesmik A more generic version than the linked duplicate or the answers here would be to create a variadic function template, see for instance http://ideone.com/eVjnbv (the commented block is for c++17). This way you simply have to convert `std::cout << a << b << c;` to `to_output(a, b, c);`. – Holt Dec 19 '16 at 13:00

2 Answers2

3

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));
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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

JKreiser
  • 111
  • 1
  • 10