Convert number to string in C++

  sonic0002        2012-08-14 15:52:48       19,221        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 [Reply]@ 2018-05-26 08:32:19
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

Project Ara, Another of Google’s Speculation. This time for modular phones

Google is very adamant with the test of their new modular phones, nicknamed as Project Ara. The company is auspicious about the new concept where consumers can design their own phones by assembling parts from different manufacturers. The company is hopeful that there will be 20 to 30 interchangeable