Search code examples
ccodeblocks

Issue with scanf_s causing no output and unexpected debugging exit in Code::Blocks C program


I'm encountering an issue while writing a C program in Code::Blocks. Although the program runs without errors, it doesn't produce any output when I use the scanf_s("%c %c %c", &a, &b, &c); statement, and it always unexpectedly exits during debugging at the scanf_s statement. How can I resolve this issue?

#include <stdio.h>
int main() {
    char a;
    char b;
    char c;
    scanf_s("%c%c%c",&a,1,&b,1,&c,1);
    printf("%c %c %c\n", a, b, c);
    return 0;
}

enter image description here

enter image description hereI'm new to C programming, and I attempted to modify the statement to scanf_s("%c%c%c", &a, 1, &b, 1, &c, 1);, which resulted in successful program execution. Could you please explain why this change resolved the issue?


Solution

    • "%c" with scanf_s() expect 2 arguments, a pointer (char *) and size (int)

    • Better code would check the result value.

    • OP may want a leading space to consume whitespaces.

    • Consider using fgets() as an alternative to reading a line of input from the user.

    if (scanf_s(" %c%c%c",&a,1,&b,1,&c,1) != 3) {
      printf("Oops\n");
    } else {
      printf("%c %c %c\n", a, b, c);
    }