PDA

View Full Version : simple problem


benjamin_lambe
07-05-2003, 05:44 PM
I have a question, i hope someone can answer it for me.

Q. If i leave out the code on line 11, scanf("%c", &temp); the program runs though and doesnt let you enter a choice, why is this? thanks to anyone who wishes to answer this.

#include <stdio.h>

int main()
{
char option, temp;
int num1, num2;

printf("\n Input two integers: ");
scanf("%d%d", &num1, &num2);
scanf("%c", &temp);
printf("\n Do you want to: \n");
printf("\t a) add them\n");
printf("\t b) subtract them\n");
printf("\t c) multiply them\n");
printf("\t d) divide them\n");

printf("\n Input your choice: ");
scanf("%c", &option);

switch(option)
{case 'a': printf("%d + %d = %d\n", num1, num2, num1 + num2);
break;
case 'b': printf("%d - %d = %d\n", num1, num2, num1 - num2);
break;
case 'c': printf("%d * %d = %d\n", num1, num2, num1 * num2);
break;
case 'd': printf("%d / %d = %d\n", num1, num2, num1 / num2);
break;
default : printf("invalid option\n");
}

return 0;
}

damonbrinkley
07-05-2003, 07:03 PM
The reason is because there's a 'newline character'(enter) in the input buffer after entering the integers. When the first scanf is in there it 'gets' the newline character and allows everything to work just fine. If it's not in there then scanf("%c", &option) 'gets' the newline character and keeps on proceeding through the program. When it gets to the switch, 'c' contains a '\n' and it sees it as an invalid choice. The way to alleviate this is to flush the input buffer after obtaining the two integers. Here's a good bit of info on doing that. http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392

benjamin_lambe
07-06-2003, 04:58 AM
Cheers for answering the question