C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers


10,705 users

How do I convert a value (a number, for example) to a std::string in cpp?

0 votes
asked May 28, 2011 by daniel Advisor (5,600 points)

1 Answer

0 votes
Best answer
There are two easy ways to do this: you can use the <cstdio> facilities or the <iostream> library. In general, you should prefer the <iostream> library.

The <iostream> library allows you to convert pretty much anything to a std::string using the following syntax (the example converts a double, but you could substitute pretty much anything that prints using the << operator):

 // File: convert.h
 #include <iostream>
 #include <sstream>
 #include <string>
 #include <stdexcept>
 class BadConversion : public std::runtime_error {
   BadConversion(const std::string& s)
     : std::runtime_error(s)
     { }
 inline std::string stringify(double x)
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();

The std::ostringstream object o offers formatting facilities just like those for std::cout. You can use manipulators and format flags to control the formatting of the result, just as you can for other std::cout.

In this example, we insert x into o via the overloaded insertion operator, <<. This invokes the iostream formatting facilities to convert x into a std::string. The if test makes sure the conversion works correctly — it should always succeed for built-in/intrinsic types, but the if test is good style.

The expression o.str() returns the std::string that contains whatever has been inserted into stream o, in this case the string value of x.
answered May 28, 2011 by albertina Geek (15,670 points)

Related questions

0 votes
1 answer 417 views
0 votes
1 answer 80 views
0 votes
0 answers 74 views
74 views asked Jun 27, 2011 by anonymous
0 votes
1 answer 103 views
103 views asked Jul 10, 2011 by Smita Advisor (7,140 points)
0 votes
1 answer 290 views
290 views asked May 27, 2011 by sagar Expert (12,340 points)