Tuesday, January 31, 2012

Converting int to string


There are two ways to convert int to string.

The first way:
  1. use itoa()
  2. copy the resulting char[] to a new string by assignment ‘=’

     Sample Program:

    This is highly recommended when we need to convert base 10 to another base.
(decimal to hexadecimal or decimal to binary)

The second way:
  1. Create stringstream variable (preprocessor directive sstream is required)
  2. Use its str()
     Sample Program:

Output of both programs:

If your problem simply needs a conversion from int to string, use the second method.

No comments:

Post a Comment