-2

I think it has something to do with with either the second scanf function or the if/else statements.

#include <stdio.h>

int main()

{
int n1;
int n2;
char op;

printf("insert first number: ");
scanf("%d", &n1);


printf("Insert operation (+, -, *, /): ");
scanf("%c", &op);


printf("insert second number: ");
scanf("%d", &n2);

if(op='+')
{
    printf("%d + %d = %d", n1, n2, n1+n2);
}
else if(op='-')
{
    printf("%d - %d = %d", n1, n2, n1-n2);
}
else if(op='*')
{
    printf("%d * %d = %d", n1, n2, n1*n2);
}
else if(op='/')
{
    printf("%d / %d = %d", n1, n2, n1/n2);
}
else
{
    printf("error [use +, -, *, /]");
}

when i run it it waits for me to input the first number, then prints the second prompt but instead of waiting for me to input the operation it skips straight to printing the third prompt and i can't figure out why.

whookimo
  • 9
  • 1
  • 2
    Second `scanf()` call leaves a newline character in the input buffer. Later consumed by the third call. – alex01011 Aug 26 '21 at 12:13
  • 3
    Side note, you are not comparing `if(op='+')`, you are assigning here. You probably meant to type, `if(op == '+')` – alex01011 Aug 26 '21 at 12:14
  • 1
    In this case, a simple `getchar()` call after the second `scanf()` should resolve the issue. – alex01011 Aug 26 '21 at 12:16
  • @alex01011 i cant believe i forgot the ==/= difference. and the newline character is / right? i can fix that by putting // instead i think? – whookimo Aug 26 '21 at 12:19
  • 1
    @whookimo user's3121023 suggestion should resolve it. Either way, you shouldn't use `scanf()` for such operations. You could try `fgets()` and later parse the input with `sscanf()`. – alex01011 Aug 26 '21 at 12:21

1 Answers1

-2

Try this instead. Try this coding in switch case. You will be getting expected results. use switch(ch); and break after each cases.