Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getchar() used to flush scanf

Status
Not open for further replies.

lotrfan

Technical User
Mar 15, 2012
1
GB
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.

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.
 
VC++ 9 and 10 compilers/RTLs work fine (of course;). No any 'e' or 'n' idiosyncrasies.

By the way: probably you want this loop condition:
Code:
while((c=getchar()) != '\n')
Remember operators priority...
 
getchar on Linux requires a CR before it actually reads anything. If you wish to read individual characters as they are typed, you need to play with ioctl for the terminal.

You may also be able to use something from the curses library.

On Windows, it should work. If getchar doesn't work, try _getch() from the conio.h library.
 
getchar() reads a single char from stdin stream but not from the keyboard. So you must press Enter to pass keyboard line buffer to stdin on Windows (getchar call returns a char after that op only) - it has the same behavior as on Linux.

getch() is the other song (non-standard conio stuff)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top