Check the return value of scanf( )

This tip submitted by citizen on 2006-04-28 18:18:55. It has been viewed 7706 times.
Rating of 2.9 with 32 votes

When you are programming it is expected of you to avoid unnecessary fragility. Interacting with the user deserves a lot of thought: if you provided a blank field and asked 100 people to write something, you would get 100 different responses.

The FAQ can teach you how to get lots of data types more safely. however, if you want to use scanf(), know that it returns how many variables it was able to read in successfully (an int). You should loop your program until scanf succeeds:

int a, b, c;
do {
   printf("Enter three digits:");
/* You will have to flush stdin somehow, with a function available on your specific compiler. _flushall() is NOT a standard C function. */
} while ( scanf("%2d %2d %2d", &a, &b, &c) < TOTAL_DATA_FIELDS );

More tips

Help your fellow programmers! Add a tip!