0

I tried to do a basic calculator using this code I was trying to do this without a switch case but things didnt work out here

#include <stdio.h>
int main() 
{
    int a,b;
    char ch;
    printf("a and b:");
    scanf("%d%d",&a,&b);
    printf("op:");
    scanf("%c",&ch);
    if(ch=='+')
    {
        printf("sum:%d",a+b);
    }
    else if(ch=='-')
    {
        printf("d:%d",a-b);
    }
    else if(ch=='*')
    {
        printf("m:%d",a*b);
    }
    else if(ch=='/')
    {
        printf("d:%d",a/b);
    }
    else
        printf("Error");
    return 0;
}

This is not giving me the right output

Output:
a and b:2 3
op:Error
+
dash: 3: +: not found
  • Try printing out `ch`... It will not be the character you expect. Hint: The `Enter` key you press after the numeric input will also be added to the input buffer, as a newline. Any decent book, tutorial or class should have told you how to solve it. And there are *many* resource all over the Internet about this issue, what have you tried searching for? – Some programmer dude Apr 01 '23 at 11:54
  • add a space in scanf before %c (scanf(" %c",ch). read about more about this in this link https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer?noredirect=1&lq=1 – Yugerten Apr 01 '23 at 22:57

0 Answers0