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

Recommended Answers

All 3 Replies

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.

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.

Thanks problem is solved!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.