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.
Printable View
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.
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.
use itoa. It's not portable so, if you just want a sigle int to char, you could do something like:
What we do is: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);
}
}
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.
>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:
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.Code:#include <iostream>
using namespace std;
int main()
{
int num = 5;
char digit = char ( num + '0' );
cout<< num <<'\t'<< digit <<endl;
}
>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.
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