0

Im trying to make a calculator but encountering error the scanf("%c",&op); doesnt take up the character on compiling the program I also tried with op=getchar(); but doesnt work either

int main()
{
    int num1,num2,result;
    char op;
    printf("Enter the first number\n");
    scanf("%d",&num1);
    printf("Enter the operation\n");
    scanf("%c",&op);
    printf("Enter the second number\n");
    scanf("%d",&num2);
    switch(op)
    {
    case '+' :
        result=num1+num2;
        printf("The addition of %d and %d is %d",num1,num2,result);
        break;
    case '-' :
        result=num1-num2;
        printf("The subtraction of %d and %d is %d",num1,num2,result);
        break;
    case '*' :
        result = num1*num2;
        printf("The multiplication of %d and %d is %d",num1,num2,result);
        break;
    case '/' :
        result=num1/num2;
        printf("The division of %d and %d is %d",num1,num2,result);
        break;
    default :
        printf("Invalid operation");
    }
    return 0;
}
  • 4
    Instead of `scanf("%c",&op);`, please try `scanf(" %c",&op);` (note the leading space in the format string). Then take some time to read more about [`scanf`](https://en.cppreference.com/w/cpp/io/c/fscanf), the `%c` format, and think about what you *really* give as input (hint: when you give the numeric input, you also press another key). – Some programmer dude May 11 '22 at 17:43
  • You need to handle the case of the division by zero, because it's undefined behaviour. – Zakk May 11 '22 at 17:49
  • And you need to handle the cases where `scanf` fails. – Zakk May 11 '22 at 17:52
  • @Someprogrammerdude could you please write your comment as an answer to mark this question as answered? – TornaxO7 May 11 '22 at 17:54
  • This problem is simpler if you take the parameters from the command line arguments rather than reading them from the input stream. There's no need to deal with the difficulties that `scanf` introduces. If you are new to the language, do not use `scanf`. http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – William Pursell May 11 '22 at 17:55
  • @TornaxO7 an alternative is to close as typo or dup – Craig Estey May 11 '22 at 18:37

0 Answers0