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

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.


scanf() leaves the "a" still in the input buffer for next time. You should probably use getline() to read a line no matter what and then parse it with strtol() or similar instead.

(Yes, getline() is GNU-specific, not POSIX. So what? The question is tagged "gcc" and "linux". getline() is also the only sensible option to read a line of text unless you want to do it all by hand.)


I think you just have to flush the buffer before you continue with the loop. Something like that would probably do the job, although I can't test what I am writing from here:

int c;while((c = getchar()) != '\n' && c != EOF);