I am new to C programming, I have made a simple calculator program in C.
The program runs but doesn't work, it works till value for b
is entered after then when character input comes it doesn't ask for the input. I don't know why this is happening but is there any fix?
here's my code:
#include <stdio.h>
int main()
{
float a,b;
char op;
printf("enter a: ");
scanf("%f",&a);
printf("enter b: ");
scanf("%f",&b);
printf("enter operation: ");
scanf("%c",&op);
switch(op)
{
case '+':
printf("\n%.2f %c %.2f = %.2f",a,op,b,a+b);
break;
case '-':
printf("\n%.2f %c %.2f = %.2f",a,op,b,a-b);
break;
case '*':
printf("\n%.2f %c %.2f = %.2f",a,op,b,a*b);
break;
case '/':
printf("\n%.2f %c %.2f = %.2f",a,op,b,a/b);
break;
default:
printf("invallid input!!");
}
return 0;
}
The program seems to be absolutely correct but still there is something there I am missing. Answers are appreciated.
Just put a space before your enter operation's scanf()
function's character format specifier and your program will work fine:
scanf( " %c" , &op );