#include <stdio.h>
int main()
{
int c1;
char op;
printf("\n(Int or Float) \n\t[1.for int 2.for float] \nEnter Choise : ");
scanf("%d",&c1);
if (c1==1)
{
printf("\n(select opearion) \n\t[+, -, *] \nEnter Choise : ");
scanf("%c", &op);
int a,b,r;
printf("\n Enter Two no. : ");
scanf("%d%d ", &a,&b);
switch (op)
{
case '+': r=a+b;
break;
case '-': r=a-b;
break;
case '*': r=a*b;
break;
default:
printf("Wrong Operator Entered");
}
printf("\n\n Result = %d \n\n",r);
}
else if(c1==2)
{
printf("\n(select opearion) \n\t[+, -, *] \nEnter Choise : ");
scanf("%c", &op);
float a,b,r;
printf("\n Enter two numbers : ");
scanf("%f%f", &a,&b);
switch (op)
{
case '+': r=a+b;
break;
case '-': r=a-b;
break;
case '*': r=a*b;
break;
default:
printf("Wrong Operator Entered");
}
printf("\n\n Result = %f\n\n",r);
}
else
{
printf("\n\n Wrong choise entered \n\n");
}
}
Upon running this program the program does not wait for taking the value of op and directly goes to the asking for Entering Two no. Why does this happen?
Why does the program skips part of taking values from the user of desired operation and goes to the next step of asking for two no.s on which the operation is to be performed.
Why does the program skips that value taking part.
After the first
scanf(), there’s a newline character left in input buffer which is consumed by the nextscanf. So, it doesn’t wait for input.Use
getchar()after the 1st call to scanf to consume the newline character.