Search code examples
cscanfformat-specifiers

How to input just character in scanf("%d%c");


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
    int input;
    char ch;
    scanf("%d%c", &input, &ch);
    printf("%d %c", input, ch);
}

I just want ch has some character and input has trash value.

So i typed [q] and [enter].

But output is [trash value ?].

I don't know why ch has '?' not 'q'.

What happens in my buffer?


Solution

  • scanf("%d%c", &input, &ch);

    With input "q", scanf will try to interpret 'q' as the first character of an integer (for the "%d" conversion) and fail... scanf() returns immediately with value 0 and without changing the value of ch (the value of input is indeterminate).
    "q" is still in the input buffer ready for the next input operayion.

    Always check the return value of scanf()

    int chk = scanf("%d%c", &value, &ch);
    switch (chk) {
        default: /* this didn't happen */;
                 /* let the compiler writers know about this */
                 break;
        case EOF: /* error */;
                  /* value unchanged */
                  /* ch unchanged */
                  break;
        case 0: /* no input found */;
                /* value indeterminate */
                /* ch unchanged */
                break;
        case 1: /* no input for ch found */;
                /* value ok; (possibly) changed */
                /* ch indeterminate */
                break;
        case 2: /* all ok */;
                /* value ok; (possibly) changed */
                /* ch ok; (possibly) changed */
                break;
    }