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;
}
argv[2]is a string, but in your switch you compare to a character.Do this instead:
or alternatively: