Search code examples
cscanfgetcharputchar

Is getchar() equivalent to scanf("%c") and putchar() equivalent to printf("%c")?


Is a = getchar() equivalent to scanf("%c",&a);?

Is putchar(a) equivalent to printf("%c",a); where a is a char variable?


Solution

  • Generally speaking yes they are the same.

    But they are not in a few nitpicky ways. The function getchar is typed to return int and not char. This is done so that getchar can both all possible char values and additionally error codes.

    So while the following happily compiles in most compilers you are essentially truncating away an error message

    char c = getchar();
    

    The function scanf, though, allows you to use a char type directly and separates out the error code into the return value.