ccharscanfconversion-specifier

The scanf function in C language uses a width specifier for char


There is a code where I enter ABCDEFGH and press enter, and the final result is HGF. When I use debug mode to observe variables. When executing the first sentence input, x='A'. After the next step, x='D', y='C'. After the next step, x='H', y='G', z='F'

#include <stdio.h>

int main() {
    char x, y, z;
    scanf("%2c", &x);
    scanf("%3c", &y);
    scanf("%4c", &z);
    printf("%c%c%c", x, y, z);
    return 0;
}

I am currently very confused as to why this is happening. As far as I know, "%3c" means to read in 3 characters, but only store the first one and discard the last two. I'm not sure if there's a problem with this code. Can you explain why the output is like this, regardless of whether the code was written incorrectly or not?


Solution

  • You tell scanf that is should read two or more characters from the input, and then store them into a one-character variable. That leads to undefined behavior.

    From this scanf (and family) reference regarding the c format:

    If a width specifier is used, matches exactly width characters (the argument must be a pointer to an array with sufficient room).

    [Emphasis mine]


    As a somewhat related tip, you should always check what scanf returns.