I\'ve a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input pro
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);
Flush the input buffer before you scan:
while(getchar() != EOF) continue;
if (scanf("%d", &number) == 0) {
...
I was going to suggest fflush(stdin)
, but apparently that results in undefined behavior.
In response to your comment, if you'd like the prompt to show up, you have to flush the output buffer. By default, that only happens when you print a newline. Like:
while (1) {
printf("-> ");
fflush(stdout);
while(getchar() != EOF) continue;
if (scanf("%d", &number) == 0) {
...
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.)
To solve partilly your problem I just add this line after the scanf:
fgetc(stdin); /* to delete '\n' character */
Below, your code with the line:
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fgetc(stdin); /* to delete '\n' character */
printf("Err...\n");
continue;
}
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;
}
But if you enter more than one character, the program continues one by one character until the "\n".
So I found a solution here: How to limit input length with scanf
You can use this line:
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);