linux - Why is scanf() causing infinite loop in Linux ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Why is scanf() causing infinite loop in Linux ?
Linux - Solution 1:
- 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.
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
}click below button to copy the code. By - Linux tutorial - team
Linux - Solution 2:
On some platforms (especially Windows and Linux) you can use fflush(stdin);:
#include <stdio.h>
int main(void)
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fflush(stdin);
printf("Err...\n");
continue;
}
fflush(stdin);
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}click below button to copy the code. By - Linux tutorial - team
Linux - Solution 3:
- 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.
Linux - Solution 4:
int c;
while((c = getchar()) != '\n' && c != EOF);click below button to copy the code. By - Linux tutorial - team
Linux - Solution 5:
Rather than using scanf() and have to deal with the buffer having invalid character, use fgets() and sscanf().
/* ... */
printf("0 to quit -> ");
fflush(stdout);
while (fgets(buf, sizeof buf, stdin)) {
if (sscanf(buf, "%d", &number) != 1) {
fprintf(stderr, "Err...\n");
} else {
work(number);
}
printf("0 to quit -> ");
fflush(stdout);
}
/* ... */