Why is scanf() causing infinite loop in this code?

scanf consumes only the input that matches the format string, returning the number of characters consumed. Any character that doesn’t match the format string causes it to stop scanning and leaves the invalid character still in the buffer. As others said, you still need to flush the invalid character out of the buffer before you proceed. This is a pretty dirty fix, but it will remove the offending characters from the output.

char c="0";
if (scanf("%d", &number) == 0) {
  printf("Err. . .\n");
  do {
    c = getchar();
  while (!isdigit(c));
  ungetc(c, stdin);
  //consume non-numeric chars from buffer

edit: fixed the code to remove all non-numeric chars in one go. Won’t print out multiple “Errs” for each non-numeric char anymore.

Here is a pretty good overview of scanf.

Leave a Comment