Parsing input with scanf in C

When you enter “c P101” the program actually receives “c P101\n“. Most of the conversion specifiers skip leading whitespace including newlines but %c does not. The first time around everything up til the “\n” is read, the second time around the “\n” is read into command, “c” is read into prefix, and “P” is left which is not a number so the conversion fails and “P101\n” is left on the stream. The next time “P” is stored into command, “1” is stored into prefix, and 1 (from the remaining “01“) is stored into input with the “\n” still on the stream for next time. You can fix this issue by putting a space at the beginning of the format string which will skip any leading whitespace including newlines.

A similiar thing is happening for the second case, when you enter “q“, “q\n” is entered into the stream, the first time around the “q” is read, the second time the “\n” is read, only on the third call is the second “q” read, you can avoid the problem again by adding a space character at the beginning of the format string.

A better way to do this would be to use something like fgets() to process a line at a time and then use sscanf() to do the parsing.

Leave a Comment