Search code examples
ccharscanfreturn-valuec89

assign numeric value of digit into char using scanf


If I have a char: char ch

and i want to assign it a numeric value of a digit, for example, if the user enters 0, i want the char to have the value 0 ('\0') and not 48 ('0')

if i try scanf("c", &ch) it will assign 48 (ascii value for 0), and if i try scanf("d", &ch) i get an error.

I know it can be done by receiving it as string, and then converting it into char, and then using ch-'0' to get the numeric value, but is it possible without this extra steps?


Solution

  • assign numeric value of digit into char using scanf

    Since C99, the direct way is

    char ch;
    scanf("%hdd", &ch);
    // or to insure reading only 1 character
    scanf("%1hdd", &ch);
    

    Before that, the below is common. @Lundin

    char ch;
    int ch_int;
    if (scanf("%d", &ch_int) == 1) {
      ch = ch_int;
    

    Or read the char and convert from its character value to its numeric value. (OP is already familiar with this)

    char ch;
    scanf("%c", &ch);
    ch -= '0';