Convert number to string in C++

  sonic0002        2012-08-14 15:52:48       19,465        1         

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 

           

  RELATED


  1 COMMENT


Angus
May 26, 2018 at 8:32 am
Hi, the whole thing is going perfectly here and ofcourse every one is sharing data, that's truly excellent, keep up writing. fotballdrakt barn


  RANDOM FUN

pdf is the third largest religion

When typing "How do I convert to ", the suggested search terms will be : How do I convert to islam How do I convert to Judaism How do I convert to pdf How do I convert to catholicism From the above list, pdf is the third largest religion now.

  SUPPORT US