How does scanf () work?

On windows

char c; int i; scanf("%d", &i); scanf("%c", &c); 

The computer skips the character from the console because '\ n' remains in the buffer. However, I found out that the code below works well.

 char str[10]; int i; scanf("%d", &i); scanf("%s", str); 

As in the case above, '\ n' remains in the buffer, but why does scanf successfully get the line from the console this time?

+4
source share
2 answers

From the gcc man page (I don't have a Windows operating system):

% c: always matches a fixed number of characters. The maximum field width indicates how many characters to read; if you do not specify a maximum value, it defaults to 1. It also does not skip leading whitespace characters.

% s: matches a character string without spaces. It skips and discards the leading space, but stops when it finds more spaces after reading something. [This section should explain the behavior you see. ]

+6
source

The question cannot be understood, but scanf ignores all whitespace characters. n is a space character. If you want to determine when the user clicks, you should use fgets.

 fgets(str, 10, stdin); 
+1
source

All Articles