Why is this program not printing the input I provided? (C)

The actual problem is that you are passing an uninitialized array as the format to scanf().

Also you are invoking scanf() the wrong way try this

if (scanf("%2s", readChars) == 1)
    printf("%s\n", readChars);

scanf() as well as printf() use a format string and that’s actually the cause for the f in their name.

And yes you are able to use it with just one argument, scanf() scans input according to the format string, the format string uses special values that are matched against the input, if you don’t specify at least one then scanf() will only be useful for input validation.

The following was extracted from C11 draft The fscanf function

  1. The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification. Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

    • An optional assignment-suppressing character *.
    • An optional decimal integer greater than zero that specifies the maximum field width
      (in characters).
    • An optional length modifier that specifies the size of the receiving object.
    • A conversion specifier character that specifies the type of conversion to be applied.

as you can read above, you need to pass at least one conversion specifier, and in that case the corresponding argument to store the converted value, if you pass the conversion specifier but you don’t give an argument for it, the behavior is undefined.

Browse More Popular Posts

Leave a Comment