Why scanf(“%d”, […]) does not consume ‘\n’? while scanf(“%c”) does?

It is consistent behavior, you’re just thinking about it wrong. 😉

scanf("%c", some_char); // reads a character from the key board.
scanf("%d", some_int);  // reads an integer from the key board.

So if I do this:

printf("Insert a character: ");
scanf("%c", &ch);                // if I enter 'f'. Really I entered 'f' + '\n'
                                 // scanf read the first char and left the '\n'
printf("Insert a number: ");
scanf("%d", &actualNum);      // Now scan if is looking for an int, it sees the '\n'
                              // still, but that's not an int so it waits for the 
                              // the next input from stdin

It’s not that it’s consuming the newline on its own in this case. Try this instead:

char ch;
char ch2;
printf("Insert a character: ");
scanf("%c", &ch);
printf("Insert another character: ");
scanf("%c", &ch2); 

It will “skip” the second scanf() because it reads in the '\n' at that time. scanf() is consistent and you MUST consume that '\n' if you’re going to use it correctly.

Leave a Comment

tech