[ Is it possible there will be an encoding error when reading a character? ]
If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
scanf("%d", &i);
If the input is more than 2147483648 (if i
is signed int
), scanf
will change errno
's value.
But what if I try to read a character, like this:
scanf("%c", &c);
Is it possible to enter a character that causes an encoding error? I've tested it with UTF-8 input, but that worked well (for ௮
, c
's decimal code is -32
, but errno
is 0
).
Answer 1
First, you need to use a different conversion specifier for wide characters:
wchar_t c;
scanf("%lc", &c);
The answer to your question is "yes", you should always check that the input is valid!
It may not be practically possible for a user to type an invalid character (a keyboard only produces valid characters), but input can come from other sources, and in most cases you can't predict those in advance. It's also possible that the input character set doesn't match what your program thinks it is (in which case you have bigger problems, but a check for invalid encodings will help catch the problem sooner).
In any case, it's good practice to check the return value from scanf
the same way you check the return value from malloc
(you do do that, right?)
if (scanf("%lc", &c) != 1)
emit_input_error_and_abort();