Switch statement

What is wrong with this C program using switch statement which terminates after typing symbol?

<#include<stdio.h>
#include<conio.h>
int main()
{ int a,b;
char ch;
printf("\nEnter a number");
scanf("%d",&a);
printf("\nEnter another number");
scanf("%d",&b);
printf("\nEnter the symbol");
ch=getchar();
switch(ch)
{
case '+':
printf("%d",a+b);
break;
case '-':
printf("%d",a-b);
break;
}
getch();
return 0;
}>

I am able to type the numbers. Then, when I type the symbol, the program terminates. Please help me. Thanks.
Last edited on
You have no loop and nothing to stop the program getting to return 0 and finishing. Why wouldn't it terminate?
@shadowmouse
I don't think the OP intended it to loop. The getch() before the return 0 is intended to keep the program from closing.

@OP
There is a difference between how scanf and getch work. scanf ignores all leading whitespace, including \n. When you enter the first number, you press the enter key. That leaves a \n in the buffer. That's fine, the next scanf ignores the leading \n, but you're leaving the second enter key (\n) in the buffer. getch() does not ignore leading whitespace. When you execute the getch() before the switch statement, you're reading that second \n and of course, it does not match any of the cases in your switch statement.

Had you had a default branch in your switch statement, you would have caught that condition.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
I'm sorry, I assumed that as they were using getch(), they would understand that that is how it works and that it wouldn't stop it, I therefore saw no reason why the program wouldn't close.
scanf(...) leaves a newline ('\n') in the stream. getchar() returns this newline.
One way to solve that is calling getchar(); before the actual getchar():
1
2
3
4
5
6
...
printf("\nEnter the symbol");
getchar(); // Note
ch=getchar();
switch(ch)
...
Last edited on
@3463
How can I solve this. Iam a beginner in C.Please help me.Thanks.
 
  scanf ("%c", &ch);


Keep in mind that's still going to leave a \n in the buffer which will be read by the getch() at the end of the program causing your program to close immediately.
Last edited on
@4682
Thanks for all your useful replies. I have solved it. Couldn't have solved it without your help. Thanks a lot.
Topic archived. No new replies allowed.