about fflush()

Hello.i was trying to make a simple menu using 2 switch case's..and all was ok until i had to read my options from the keyboard..the first read was ok (1 or 2).but after that disaster :)..so i new that the problem was somewhere at the getchar(),and the thing that u must press enter.(reading with echo)..so after a long time searching and trying i found a solution.putting the fflush(stdin) function in the program.and i want to now why and what it does..here is my code and it works fine now.i hope is the right way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int main ()
{
    char Color;
    int Fruit;
    printf("Chose what fruit you want:\n");
    printf("1-Apple\n");
    printf("2-Orange\n");
    scanf("%d",&Fruit);
    switch(Fruit){
	case 1: printf("Ok..so we have 2 types of apples:\n");
		printf("R-Red apples\n");
		printf("G-Green apples\n");
		fflush(stdin);    //here
		Color=getchar();
		switch(Color){
			case 'r':
			case 'R' : printf("Ty for buying.10 $ please %c\n",1);
				break;
                        case 'v' :
			case 'V' : printf("Ty for buying.120$ please %c\n",1);
				break;
			default : printf("Wrong option.\n");
		}
	        break;
	case 2: printf("Damn..where out of oranges\n");
		printf("1-Report the problem\n");
		printf("2-Then get out of my shop\n");
		//and maybe another switch/case
		break;
		default : printf("Wrong option.\n");
    }
    fflush(stdin);   //here
    printf("\nPress Enter to continue");
    getchar();
    return 0;
}
Last edited on
http://cplusplus.com/fflush

And you might want to try using fflush(stdin) after you read from the keyboard (i.e. put switch lines 13 and 14)
Topic archived. No new replies allowed.