Altera_Forum
Honored Contributor
12 years agohow to flush stdin buffer between two scanf?
Hi,
I think this is a beginner-level question. Much appreciate your answers in advance! The following is my simple C-code:#include <stdio.h># include <string.h>
void main(void)
{
char sex;
char area;
do
{
printf("Please select your area (QLD, NSW, ACT, SA, WA, NT or TAS): ");
scanf("%s", area);
} while(strcmp(area,"QLD")!= 0 && strcmp(area,"NSW")!= 0 && strcmp(area,"ACT")!= 0 &&
strcmp(area,"SA")!= 0 && strcmp(area,"WA")!= 0 && strcmp(area,"NT")!= 0 && strcmp(area,"TAS")!= 0);
do
{
printf("Please enter your sex (M/F): ");
scanf("%c", &sex);
} while(sex != 'M' && sex != 'F') ;
}
This problem is: the prompt "Please senter your sex (M/F)" always gets printed twice on the screen before a value is entered. I realized it is because when I enter the string for area, the last character ENTER gets stored in stdin buffer and is treated as the value for sex. To make the program function as expected, I have to insert another scanf("%c", &sex") between the two do-while loops to clear the stdin buffer. I tried to find a neater way to do this. Some online results suggest fflush(stdin) is not a good thing to do. Is there a better way to clear the stdin buffer, or a better coding structure to avoid such problem completely?