Converting a String To Number and Vice Versa in C++


http://stackoverflow.com/questions/5290089/how-to-convert-a-number-to-string-and-vice-versa-in-c


  1. Do not use the itoa or itof functions because they are non-standard and therefore not portable.
  2. Use string streams


    How to convert a string to a number in C++


    #include <sstream>
    #include <string>
    int main()
    {
       std::string inputString = "1234 12.3 44";
       std::istringstream istr(inputString);
       int i1, i2;
       float f;
       istr >> i1 >> f >> i2;
       //i1 is 1234, f is 12.3, i2 is 44  
    }

    How to convert a number to a string in C++

     #include <sstream>  //include this to use string streams
     #include <string> 
    
    int main()
    {    
        int number = 1234;
    
        std::ostringstream ostr; //output string stream
        ostr << number; //use the string stream just like cout,
        //except the stream prints not to stdout but to a string.
    
        std::string theNumberString = ostr.str(); //the str() function of the stream 
        //returns the string.
    
        //now  theNumberString is "1234"  
    }










Comments