I am learning C and I was practicing the switch and I run the program but does not let me input *, +, -, here is my code. I can input 1st and 2th number but not the operator, after I input the numbers the program finishes. Not sure why. Thank you
#include <stdio.h>
int main(int argc, char *argv[])
{
int num1, num2, ans=0;
char ch, name;
printf("Enter a value: ");
scanf("%d",&num1);
printf("Enter a second value: ");
scanf("%d",&num2);
printf("Input * To multiply\
+ To add\
- To subtract");
scanf("%c",&ch);
switch(ch)
{
case'*':
ans=num1 * num2;
printf("%d times %i equals: %i",num1,num2,ans);
break;
case'+':
ans=num1+num2;
printf("%i plus %i equals: %d",num1,num2,ans);
break;
case'-':
ans=num1-num2;
printf("%d minus %d equals: %d",num1,num2,ans);
break;
default:
printf("Range numbers");
}
return 0;
}
This:
is reading the newline character from the entry of
num2: you need to skip it before readingch.Change to:
Adding the space before the
%cinstructsscanfto skip newlines and whitespace.