Nan Xiao Nan Xiao - 28 days ago 9
C Question

Why can't scanf assign values to the input arguments?

My

C
code is like this:

#include <stdio.h>
#include <string.h>

int main(void) {
char s[10];
int i = 0, j = 0, k = 0;

memset(s, 0xff, sizeof(s));
scanf("%9s%d%d%d", s, &i, &j, &k);
printf("%s,%d,%d,%d\n", s, i, j, k);
}


To avoid buffer overflow, I use
%9s
in
scanf
. But I find if the input string length is shorter than
10
, the result is as I have expected:

# ./test
short 1 2 3
short,1,2,3


While the length is longer or equal to
10
,
i
,
j
and
k
can't get the input:

# ./test
verylongstr 1 2 3
verylongs,0,0,0


How to understand
scanf
's behaviour?

Answer

You tell scanf to read at most 9 characters into s, so that's what it does. Once it has read 9 characters, it tries to read an integer into i, but the next input character is t (the tenth character). That cannot be converted to an integer, so the scan is terminated and scanf returns 1, indicating that it successfully read a single value.

Unfortunately you never check the return value. You should fix that.

The t is returned to the internal buffer, so the next scanf call will start with that character.