简体   繁体   中英

Trouble creating a basic command line argument based calculator

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:

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

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

or alternatively:

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

  // rest of your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM