Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble creating a basic command line argument based calculator

Tags:

c

Im trying to create a simple calculator which receives 3 arguments from the user, [Number 1] [operator] [Number 2]. The operator signifies the calculation to be done (+,-,x,/). I decided to use a switch case for the operator. However I cannot seem to get my code to work. It seems simple enough however the output is always the default switch case.

Thanks for the help.

#include <stdio.h>

int main(int argc, char *argv[]) {
    int a,b,sol;
    char op;
    if ( argc != 4) {
         printf("Usage: calc [operand_1] [operator] [operand_2]\n");
         break;
    } 

    a = atoi(argv[1]);
    b = atoi(argv[3]);
    op = argv[2];

    switch (op)
    {
    case '+':
        sol=a+b;
        printf("%i\n",sol);
        break;
    case '-':
        sol=a-b;
        printf("%i\n",sol);
        break;        
    case 'x':
        sol=a*b;
        printf("%i\n",sol);
        break;       
    case '/':
        sol=a/b;
        printf("%i\n",sol);
        break;        
    default:
        printf("Invalid Operator \n");
    }

    return 0; 
}
like image 531
MordFustang Avatar asked Dec 14 '25 10:12

MordFustang


1 Answers

argv[2] is a string, but in your switch you compare to a character.

Do this instead:

if(strcmp(op,"+") == 0)
   sol=a+b;

// etc
printf("%i\n",sol);

or alternatively:

  op = *argv[2]; // get first char

  // rest of your code
like image 173
thumbmunkeys Avatar answered Dec 16 '25 08:12

thumbmunkeys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!