Search code examples
cinputscanfgetchar

Why is my second printf not called when expected?


I'm just learning to program in C and am a bit confused about something going on with scanf and getchar. I understand that using something like scanf("%d", &i) will read an integer input, but leave the following newline character in the input buffer (which is why one must clear the input buffer by looking for getchar() == '\n' before using getchar after a scanf call.

Here is my simple (incorrect) program that reads an integer, and then a character input, and prints them back to the user:

int main(void)
{
    int i;
    printf("Enter an integer: ");
    scanf("%d\n", &i);

    printf("Enter a char: ");
    char ch = getchar();

    printf("You entered integer: %d\nYou entered character: %c\n", i, ch);

    return 0;
}

If I leave the newline character off in my scanf format String (so just have "%d"), it makes sense that as soon as the user types in an integer and hits enter that integer will be read and stored in i, and the program will continue to execute ("Enter a char: " immediately printed, and ch storing the newline character).

However, with the format String of "%d\n" I encounter unexpected behavior. When a user enters an integer and hits enter, I expected "Enter a char: " to be printed. Instead, you can keep hitting enter and nothing happens until you decide to enter a different character. So you can type "10", hit enter 6 times, then type in "d" and getchar() reads that "correctly". The whole program output would look like this

Enter an integer: 10




d
Enter a char: You entered integer: 10
You entered character: d

Why is it that my program stalls until a character is entered? It seems odd that my second printf function is called seemingly AFTER the call to getchar (since the character read is entered before "Enter a char: " gets printed).

Any help would be greatly appreciated. I am just trying to further my understanding of this nuance in C.


Solution

  • In a scanf format string, any sequence of white-space characters will match any amount of white space in the input. So your \n will match any number of new-lines, and scanf will only return once it encounters a non-space character.