Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does scanf() really work?

Tags:

c

stdio

scanf

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?

like image 906
Jaebum Avatar asked Jan 22 '23 17:01

Jaebum


1 Answers

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

like image 95
terminus Avatar answered Feb 04 '23 03:02

terminus