itoa C++ – Integer to String Conversion

itoa C++ typecast function is used for integer to string conversion. The converted string can be in binary, decimal or hexa decimal form depending upon base i.e. 2, 10 or 16 respectively.

itoa() C++ Syntax :

/*-------------------------------------------
* function - itoa - convert int to string
*
* @ param : int - input value
* @ param : char* - buffer to store result
* @ param : int - conversion base i.e. 2,10,16
* 
* @ return char* - returns string pointer.
* */
char *  itoa ( int value, char * str, int base );

function itoa() C++ program example

This code demonstrate how to convert integer to string in C++ programs using itoa() library function. Int value will be converted to null terminating string in form of binary, decimal and hexadecimal.

/*-------------------------------------
* C++ Integer to String program using
* itoa function
*
* Conversion examples:
* int to decimal string
* int to binary string
* int to hexadecimal string
* */

#include<string>
#include<iostream>
using namespace std;

int main()
{
      int val;
      //Buffer to store converted string results
      char buff[64];
      cout<<"Enter a number: ";
      cin>>val;

      //Convert int to decimal string
      itoa (val,buff,10);
      cout<<"Decimal value: "<<buff<<endl;     

      //Convert int value to binary string
      itoa (val,buff,2);
      cout<<"Binary value: "<<buff<<endl;     

      //Convert int to hexadecimal string
      itoa (val,buff,16);
      cout<<"Hexadecimal value: "<<buff<<endl; 


      return 0;
}

Output:
Enter a number: 555
Decimal value: 555
Binary value: 1000101011
Hexadecimal value: 22b

NOTE:

Result of char buff can be stored in C++ std::string as shown below.

int main()
{
      int val =555;
      char buff[64];
      itoa (val,buff,10);
      cout<<"Decimal value: "<<buff<<endl;     

      //Store result in C++ std::string variable
      string result(buff);
      cout<< "String value:"<<result.c_str()<<endl;

      return 0;
}

int to string conversion using stringstream – without C++ itoa :

To work with stringstream <sstream> header file need to be included in C++ program.

#include<iostream>
using namespace std;
//include for stringstream
#include <sstream>

int main()
{
      int val =555;  
      string str;
      //declare stringstream object
      std::stringstream output;

      //push int value to stream
      output << val;     

      str = output.str();
      //display
      cout<<"Decimal value: "<<str.c_str()<<endl;   
      return 0;

}

Related Posts