Reputation: 1570
On Windows,
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
The computer skips to retrieve character from console because '\n' is remaining on buffer. However, I found out that the code below works well.
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
Just like the case above, '\n' is remaining on buffer but why scanf successfully gets the string from console this time?
Upvotes: 4
Views: 8470
Reputation: 403
From the gcc man page (I don't have Windows handy):
%c: matches a fixed number of characters, always. The maximum field width says how many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters.
%s: matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something. [ This clause should explain the behaviour you are seeing. ]
Upvotes: 7
Reputation: 2971
Having trouble understanding the question, but scanf ignores all whitespace characters. n
is a whitespace character. If you want to detect when user presses enter you should use fgets.
fgets(str, 10, stdin);
Upvotes: 2