search
Login

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

0 votes
58 views
asked Advisor 5.6k points 1 7 14

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 {
 public:
   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 Geek 15.7k points 5 9 21

Related questions

0 votes
1 answer 422 views
422 views
which loop is better in C and C++, for loop or while loop or do while?
asked anonymous
0 votes
1 answer 84 views
84 views
When should I use references, and when should I use pointers?
asked albertina Geek 15.7k points 5 9 21
0 votes
0 answers 75 views
0 votes
1 answer 104 views
104 views
How can I search for data in a linked list?
asked Smita Advisor 7.1k points 10 22 42
0 votes
1 answer 292 views
292 views
please explain what is "passing by value", "passing by pointer" and "passing by reference"
asked sagar Expert 12.3k points 7 12 24
...