Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Programming =>  C++

Convert number to string in C++

  sonic0002      2012-08-14 15:52:48      9,300    0    0

Prior to C++11, there is no built-in function in C++ standard library which can be used to convert numbers such as interger and double number to string.  There are many ways which can convert number to string. Since C++ is C compatible, we can use itoa() function to convert an integer to C style string. But this one can only convert integer to string, not double. For different types of numbers, we need to use different functions.

string s = string(itoa(a));

Actually, we can also use stringstream in C++ to convert number to string.  Also, here since we want to convert different types of numbers to string, we may need template. Below is the implementation:

    /*
     * Method      : toString()
     * Description : Convert other data type to string
     * Input         : T -- template data type
     * Return        : string
     */
    template
    static string toString(T data){
        stringstream s;
        s<<data;
        return s.str();
    }


So later when we want to convert an integer or double number to string, we can use it this way.

toString(42);

toString(42.01);

toString("42");

Fortunately, in C++11, we can use the built-in std::to_string() method to convert number to string. The overloaded types defined are:

std::string to_string( int value );
(1) (since C++11)
 
std::string to_string( long value );
(2) (since C++11)
 
std::string to_string( long long value );
(3) (since C++11)
 
std::string to_string( unsigned value );
(4) (since C++11)
 
std::string to_string( unsigned long value );
(5) (since C++11)
 
std::string to_string( unsigned long long value );
(6) (since C++11)
 
std::string to_string( float value );
(7) (since C++11)
 
std::string to_string( double value );
(8) (since C++11)
 
std::string to_string( long double value );
(9) (since C++11)

For example:

double f = 23.43;	
std::string f_str = std::to_string(f);

Reference : http://en.cppreference.com/w/cpp/string/basic_string/to_string

C++ CONVERSION NUMBER STRING

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

Stats for nerds

By sonic0002
The YouTube HTML5 player is naughty. As a nerd, you can view the stats of the video playing now. These stats are not how many views or likes but how many frames are dropped and bandwidth etc. Google always brings us some surprise.