Validate the type of input in a do-while loop

The problem is that “scanf()” can leave unread data in your input buffer. Hence the “infinite loop”.

Another issue is that you should validate the return value from scanf(). If you expect one integer value … and scanf returns “0” items read … then you know something went wrong.

Here is an example:

#include <stdio.h>

void discard_junk () 
{
  int c;
  while((c = getchar()) != '\n' && c != EOF)
    ;
}

int main (int argc, char *argv[])
{
  int integer, i;
  do {
      printf("Enter > ");
      i = scanf("%d", &integer);
      if (i == 1) {
        printf ("Good value: %d\n", integer);
      }
      else {
        printf ("BAD VALUE, i=%i!\n", i);
        discard_junk ();
      }
   } while (i != 1);

  return 0;
}

Sample output:

Enter > A
BAD VALUE, i=0!
Enter > B
BAD VALUE, i=0!
Enter > 1
Good value: 1

‘Hope that helps!

Leave a Comment