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.
%c and %s are part of the printf() functions in the standard library, not part of the language itself.
In order to declare a variable with character type, you use the char keyword followed by the variable name. The following example declares three char variables. char ch; char key, flag;.
\0 is zero character. In C it is mostly used to indicate the termination of a character string.
Just put a space before your enter operation's scanf()
function's character format specifier and your program will work fine:
scanf( " %c" , &op );
When using scanf()
, it will leave behind a \n
character in the input buffer. The next scanf()
will keep this newline and store it. You need to either add a space to scanf()
:
scanf(" %c", &op); /* to skip any number of white space characters */
Or consume the character instead with getchar()
. The function getchar()
returns int
and EOF
on error It can be used this way:
int op = getchar()
Which stores the character found in op
. You could also just add getchar()
after your scanf()
calls, which will consume the leftover \n
character.
Note: It is good practice to check result of scanf()
. You should write instead:
if (scanf(" %c", &op) != 1) {
/* oops, non character found. Handle error */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With