0

Hi
I've been think about this for a while but the answer eludes me.
I know its a pretty simple program but here's the snippet:

int main(void){
	printf("Enter the operation of your choice\n");
	int a;
	int b;
	int ch;
	
	while((ch = getChoice()) != 'q'){
		
		printf("enter a value: ");
		if(scanf("%d", &a) != 1)
			break;
		printf("\n");
		printf("enter another value: ");
		if(scanf("%d", &b) != 1)
			break;
		printf("\n");
		
		switch(ch){
			case 'a' :
				add(a, b);
				break;
			case 'b' :
				subtract(a, b);
				break;
			case 'c' :
				multiply(a, b);
				break;
			case 'd' :
				divide(a, b);
				break;
			default  :
				printf("program error!\n");
				break;
		}
		
	}
	printf("thanks have a good day\n");
	return 0;		
}		
		
		
char getChoice(void){
	int ch;
	
	printf("a. add		b. subtract\n");
	printf("c. multiply 	d. divide\n");
	printf("q (to quit)\n");	

	ch = getFirst();

	while((ch < 'a' || ch > 'd') && ch != 'q'){
		printf("inappropriate response, try again\n");
		ch = getFirst();
	}
	return ch;		
}

char getFirst(void){
	char ch;
	ch = getchar();
	while(getchar() != '\n')
		continue;
	return ch;
}

When I run the program, the first time through with any selection works as its supposed to. However the second time through i get an
"inappropriate response" even if the the letter is correct and am prompted to enter another selection. The second time it always works. I figure that there's a newline character in the input queue but I don't know how to fix that. Any help would be great.
Thanks

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by jcollins85
0

Your second call to getFirst() first consumes the \n left behind by the previous scanf() call.

Mixing input methods is always a disaster waiting to happen.

0

When we use getchar() then whatever input we give it goes in a buffer and getchar function reads from that buffer.
when first time u entered ur choice it stored in buffer (say u choose a,then buffer will contain a,\n).so first time , getchar picks the choice u supplied but remember \n is still in buffer.so when getchar() is again called then say u entered ur choice 'b'.then the buffer content will be (\n,b,\n). so this time getchar() picks '\n'. that's y u r getting an error.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.