0

Looking through related Q&A's, it seems that best C++ practice for conversion to string is

ostringstream stringStream;
stringStream << input_value;        // let's say, input_value is a double
output_string = stringStream.str();

Is there any way to achieve the same in less than three lines of clean C++?

Joachim W
  • 7,290
  • 5
  • 31
  • 59
  • Duplicate of http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c and http://stackoverflow.com/questions/332111/how-do-i-convert-a-double-into-a-string-in-c – HAL Aug 23 '13 at 12:15
  • 1
    Put the above three lines in a function, then it'll only take one line. – Crowman Aug 23 '13 at 12:16
  • Thanks for the many useful answers! Seems I am allowed to accept only one, that will forcibly be an arbitrary choice, sorry. – Joachim W Aug 23 '13 at 12:23

4 Answers4

12

Using the std::to_string family of functions:

std::string s = std::to_string(3.1416);

If you don't have the required C++11, another option is boost::lexical_cast.

std::string s = boost::lexical_cast<std::string>(3.1416);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
10

Yes, with std::to_string:

output_string = std::to_string(input_value);

(For C++03, look into boost::lexical_cast).

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
3

If you don't have C++11, you can use something like:

boost::lexical_cast<std::string>(input_value);

(it's easy enough to write your own to_string if you don't want Boost though - you're really just wrapping your existing code in a function).

If you do have C++11, stick with the std::to_string Jesse Good & juanchopanza already mentioned.

Useless
  • 64,155
  • 6
  • 88
  • 132
  • boost is not part of the standard C++. And wrapping everything in a function hiding everything can always be done by anyone, but... it doesn't explain anything – Emilio Garavaglia Aug 23 '13 at 12:16
  • `to_string` and `lexical_cast` are functions - what's the difference? – Useless Aug 23 '13 at 12:17
  • to_string and std::stringstream are part of the C++ standard. Boost is not. And if we admit to take elsewhere delivered functions, we are playing a different game. – Emilio Garavaglia Aug 23 '13 at 12:22
0

Both are one-liners in C++ 11:

std::string s1 = std::to_string(42);

and

std::string s2 = std::to_string(42.0);
Sergey K.
  • 24,894
  • 13
  • 106
  • 174