scanf
returns the number of "items", i.e. values passed both in the format string (a single item is e.g. %d
, %c
and so on), and in the subsequent arguments to scanf
, for example, to read two integers separated by comma and space, you would use:
int x, y;
int items = scanf("%d, %d", &x, &y);
assert(items == 2);
I've already spoiled what my suggestion will be above - instead of adding unused variables, if you just want to read it, add an assertion:
#include <assert.h>
/* ... */
assert(scanf("%d", &sides) > 0);
/* ... */
Unfortunately, assert(scanf("%d", &sides));
is not enough, because of EOF (this will return -1
). It would be really elegant.
I think this is the way to go, if you don't want to continue your program with an uninitialized variable (sides
) in this case.
Alternatively, you can capture scanf
's result to a variable, and handle it gracefully like in the other answers.