Consider the following code where the function flush containing getchar is being used to flush scanf when an attempted read from the terminal was unsuccessful. I was wondering if anyone could shed any light on the behavior discussed below. Thanks and apologies in advance if I have overlooked something very obvious.
My question deals with the following behavior when values other than the expected floating point value is entered after the prompt during execution.
1.) When you type the word "test" after the prompt during execution you will see the expected output suggesting the four characters in test where found in the buffer before the new line.
2.) When you type the word "eek" at the prompt, you will see only two characters are found (at least using my compiler I see that)
3.) When you type the word "nine" at the prompt, no indication is given that any of the characters in the word nine are found.
It seems that the letters e and n (and their location in the string) are causing the problem.
Code:
#include <stdio.h>
void flush (void) {
int c;
while(c=getchar()!= '\n') {
printf("Character read %d \n",c);
}
}
int main() {
int success;
float a;
success=0;
while(success==0) {
printf("Enter numeric value for a: ");
success=scanf("%f",&a);
flush();
}
return 0;
}
My question deals with the following behavior when values other than the expected floating point value is entered after the prompt during execution.
1.) When you type the word "test" after the prompt during execution you will see the expected output suggesting the four characters in test where found in the buffer before the new line.
2.) When you type the word "eek" at the prompt, you will see only two characters are found (at least using my compiler I see that)
3.) When you type the word "nine" at the prompt, no indication is given that any of the characters in the word nine are found.
It seems that the letters e and n (and their location in the string) are causing the problem.