# Help convert char to int

• 03-30-2004
mannyginda2g
Help convert char to int
I know how to convert a char to an int using atoi but how do I convert a single digit int to a char???? thanks.
• 03-30-2004
try itoa() if your compiler comes with the non-standard conio.h file and your are willing to use non-standard material or use the standard compliant stringstream class and extract the char you want from the string which is derived.
• 03-30-2004
-=SoKrA=-
use itoa. It's not portable so, if you just want a sigle int to char, you could do something like:
Code:

```char int_to_char(int input) {   if(input<0 || input>9){     std::cerr<<"Wrong int taken as input"<<std::endl;     return '0';   }else{   return reinterpret_cast<char>(input + 48);   } }```
What we do is:
First, we check that the number is appropiate for conversion.
If the number is not right, then we output error and return a zero (char), because we need to return something.
We add 48 to the int. This gives us the ascii code for the number (48 ascii is 0 int).
Then we let the compiler reinterpret the number as a char, that way, the correct number will be returned.

This will only work for numbers between 0 and 9. No other numbers will be made into chars.
• 03-30-2004
Prelude
>I know how to convert a char to an int using atoi but how do I convert a single digit int to a char????
Provided the int is really a single digit you can simply add '0' to it:
Code:

```#include <iostream> using namespace std; int main() {   int num = 5;   char digit = char ( num + '0' );   cout<< num <<'\t'<< digit <<endl; }```
If at any point you want multiple digit numbers to a string you will need to use sprintf or stringstreams. Don't use itoa because there are standard alternatives.

>return '0';
Not a good error code. Perhaps returning an obviously invalid char, or throwing an exception would be better suited.

>return reinterpret_cast<char>(input + 48);
reinterpret_cast is used for type conversions between two types that are unrelated. There's no need for it here. A static_cast would be better for removing the warning. And why use 48? That just makes the function less portable. Use '0' instead to avoid assuming ASCII.
• 03-31-2004
major_small
I was going to point out what Prelude just did... instead of using char(input+48), which requires you to memorize that the character '0' is dec 48 in the ASCII chart, you could just do char(input+'0')

that also is more readable... unless you put a comment saying that 48 is the ASCII dec equivalent for '0', people might not know what you're talking about