Reputation: 1
I'm brand new to C++ and am trying to make a program that when the user inputs an int between 0-9 it displays the number, and between 9 and 36 displays the corresponding letter, A= 10 B= 11... I know how to use the switch function but with 26 cases that's a lot of typing. How would I use static_cast to convert the Int variables to Chars?
Upvotes: 0
Views: 2762
Reputation: 471229
If I'm understanding your question correctly, this will probably do what you want.
int num = 12; // Input number
char ch;
if (num < 10)
ch = num + '0';
else
ch = num + 'a' - 10;
or alternatively:
const char DIGITS[] = "0123456789abcdefghijklmnopqrstuvwxyz";
int num = 12; // Input number
char ch = DIGITS[num]; // Output number/letter
So there's no need to cast anything.
If you want capital letters instead, replace the 'a'
with 'A'
in the first example. The second example is trivial to switch to capitals.
Upvotes: 4
Reputation: 385144
Don't. Just output them. Streams already do lexical conversion for you.
int x = 64;
std::cout << x; // outputs "64"
char c = 'B';
std::cout << c; // outputs "B"
Upvotes: 1
Reputation: 182763
Like this:
char IntToChar(int j)
{
if( (j >= 0) && (j <= 9) ) return '0' + static_cast<char>(j);
if( (j >= 10) && (j <= 36) ) return 'A' + static_cast<char>(j - 10);
/* whatever you want here */
}
Upvotes: 0