Here, I saw this statement in the accepted answer:
Most of the conversion specifiers skip leading whitespace including newlines but
%c
does not.
For me it is not clear the rationale under this different behaviors, I would have expected a uniform one (e.g. always skipping or never).
I came into this kind of problem with a piece of C code like this:
#include "stdio.h"
int main(void){
char ch;
int actualNum;
printf("Insert a number: ");
scanf("%d", &actualNum);
// getchar();
printf("Insert a character: ");
scanf("%c", &ch);
return 0;
}
Swapping the two scanf
s solves the problem, as well as the (commented) getchar
, otherwise the '\n'
of the first insertion would be consumed by the second scanf
with %c
. I tested on gcc both on linux and windows, the behavior is the same:
gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
So my question is: Why does %d
and %c
behave differently w.r.t. '\n'
in scanf
?