Reputation: 103
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.
Upvotes: 5
Views: 1903
Reputation: 1
You can fix the issue using fflush(stdin); before scanf("%c",c);. You only have to use this when you have to switch from int/floot input to character/string input.
#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: ");
fflush(stdin);
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;
}
Upvotes: 0
Reputation: 26315
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 */
Upvotes: 2
Reputation: 801
Just put a space before your enter operation's scanf()
function's character format specifier and your program will work fine:
scanf( " %c" , &op );
Upvotes: 3