The %s
conversion specifier in the format string reads a sequence of non-whitespace characters and stores in buffer pointed to by the corresponding argument passed to sscanf
. The buffer must be large enough to store the input string plus the terminating null byte which is added automatically by sscanf
else it is undefined behaviour.
char readList[3];
The above statement defines readList
to be an array of 3
characters. What you need is an array of characters arrays large enough to store the strings written by sscanf
. Also the format string "List %s, %s, %s \n"
in your sscanf
call means that it must exactly match "List"
and two commas '
in that order in the string linebuf
else sscanf
will fail due to matching failure. Make sure that you string linebuf
is formatted accordingly else here is what I suggest. Also, you must guard against sscanf
overrunning the buffer it writes into by specifying the maximum field width else it will cause undefined behaviour. The maximum field width should be one less than the buffer size to accommodate the terminating null byte.
// assuming the max length of a string in linebuf is 40
// +1 for the terminating null byte which is added by sscanf
char readList[3][40+1];
fgets(linebuf, sizeof linebuf, fp);
// "%40s" means that sscanf will write at most 40 chars
// in the buffer and then append the null byte at the end.
sscanf(linebuf,
"%40s%40s%40s",
readList[0],
readList[1],
readList[2]);