tags:

views:

245

answers:

2

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?

A: 

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);
Martin
sry for bad eng :( I think I should've use word 'get' rather than 'retrieve'. I just confused the meanings.
Lee Jae Beom
+6  A: 

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. ]

terminus
Thanks a lot :)
Lee Jae Beom