A typical idiom is:
if (scanf("%d%d%d", &a, &b &c) != 3)
handle_the_failure();
This 3
, the number of fields, is redundant. If I change the pattern and the arguments to scanf(..)
, but forget to change the 3
, that's another compile-test-debug cycle, which is a waste of time.
Is there an idiom that allows to check the (absolute) success of scanf(..)
without having to write the number of fields in the code? Maybe something like this:
scanf("%d%d%d", &a, &b &c);
if (lastScanfFailedInAnyWay())
handle_the_failure();
The documentation (see "Return value" section) talks about four different conditions:
End-of-file
Reading error
Matching failure
Encoding error interpreting wide characters
The first two are addressed by feof(..)
and ferror(..)
(I'm assuming feof(..)
implies ferror(..)
), and the last — by setting errno
to EILSEQ
. But I'm interested in a catch-all (i.e. including figuring out if a matching failure occurred).
P.S. Looking at the neat out-of-context example above, this may seem like too much to ask, but consider real practice, where you make many changes rapidly, and there are hundreds of little things like this to keep in mind, that every time you change one thing, you have to change another one elsewhere. Then it becomes clear that developing habits that eliminate dependencies of various sorts pays off.