How to validate input using scanf

Using scanf() is usually a bad idea for user input since failure leaves the FILE pointer at an unknown position. That’s because scanf stands for “scan formatted” and there is little more unformatted than user input.

I would suggest using fgets() to get a line in, followed by sscanf() on the string to actually check and process it.

This also allows you to check the string for those characters you desire (either via a loop or with a regular expression), something which the scanf family of functions is not really suited for.

By way of example, using scanf() with a "%d" or "%f" will stop at the first non-number character so won’t catch trailing errors like "127hello", which will just give you 127. And using it with a non-bounded %s is just begging for a buffer overflow.

If you really must use the [] format specifier (in scanf or sscanf), I don’t think it’s meant to be followed by s.

And, for a robust input solution using that advice, see here. Once you have an input line as a string, you can sscanf to your hearts content.

Leave a Comment