简体   繁体   中英

Static_Cast C++ how to change an INT variable to display CHAR

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?

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.

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"

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 */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM