-3

I am new to c language and I wanted to make a calculator so I wrote this code:

#include<stdio.h>
void main()
{
    int x,y,z;
    char m;
    printf("enter the first number");
    scanf("%d",&x);
    printf("enter the second number");
    scanf("%d",&y);
    printf("enter the math operator");
    scanf("%c",&m);
if (m == '+')
{
    z=x+y;
    printf("the answer is %d",z);

}
else if(m == '-')
{
    z=x-y;
    printf("the answer is %d",z);
}
else
{
    printf("wrong symbol");
}
    }

when I run the program it will ignore

scanf("%c",&m);

and

if (m == '+')
{
    z=x+y;
    printf("the answer is %d",z);

}
else if(m == '-')
{
    z=x-y;
    printf("the answer is %d",z);
}

and it will go straight to

else
    {
        printf("wrong symbol");
    }

and it shows like this: https://i.stack.imgur.com/RmsWm.jpg please help.

1 Answers1

0

You just need to flush the stream entry stdin because some char are still in stdin when you call scanf("%c",&m);. And since it looks only for one char ... It directly takes the first char already in stdin ('\n').

Insert this portable code to flush stdin before call scanf :

int c;
while((c = getchar()) != '\n' && c != EOF);

Hope this help !

Yohboy
  • 264
  • 4
  • 13