I thought of making a calculator, just a simple one with loops and the basic operations, but the weird thing is that the scanf
of character in between my scanf
for number is being ignored. It works fine if I put it on top of the scanf
of integer but it wouldn't look anything like a calculator. Is there any way to solve this issue? It's not yet finished; got an error up to here, so wondering what's wrong.
#include <stdio.h>
#include <stdlib.h>
int main(){
int number1,number2,total;
char a;
printf("This is your personal calculator:(End with ""="")\n");
scanf("%d",&number1);
scanf("%c",&a);
scanf("%d",&number2);
if (a == 'x' || a == 'X' || a == '*'){
total=number1*number2;
printf("%d",total);
} else if (a == '/'){
total=number1/number2;
printf("%d",total);
} else if (a == '+'){
total=number1+number2;
printf("%d",total);
} else if (a == '-'){
total=number1-number2;
printf("%d",total);
} else {
printf("error");
}
system("pause");
return 0;
}
You should test that you get a value from scanf()
, every time.
The %c
character reads the blank or newline after the first number; use " %c"
with a leading space to skip over optional white space before reading the character.
if (scanf("%d", &number1) == 1 &&
scanf(" %c", &a) == 1 &&
scanf("%d", &number2) == 1)
{
...process possibly valid input...
}
else
{
...diagnostics...
}
It will probably be easier to give good diagnostics if you read whole lines with fgets()
and parse them with sscanf()
.
number2
was not containing what you expected, for example.number1
and number2
to -1
so you can see when the scanf()
failed (since you aren't yet checking whether scanf()
succeeded).The problem is because of the newline char
\n
left over by the scanf
. This could be avoided by placing a space before format specifier %c
.
Try this
scanf(" %c", &a);
^ An space
this will help you to eat up \n
char left over by first scanf
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