1

I have an assignment to create a calculator program in C that takes a total of 4 command line arguments, parses the integers and arithmetic operator, performs the operation and prints the solution in the form of 1 + 1 = 2. My program works as expected except in the case of * for multiplication. I understand that * is a special character in bash, and when i escape it with \ my program works correctly. For example: $ lab3 1 \* 3 returns 3. However, asking the user to escape the asterisk does not satisfy the requirements of my assignment. Is there a way to parse the * into a char variable?

My program in its entirety:

#include <stdio.h>

int main(int argc, char **argv)
{
    int     n1, n2;
    char    operand[1];
    char    garbage[100];

    if(argc != 4) {
        printf("invalid input!");
        return 0;
    }
    else if(sscanf(argv[1], "%d %s", &n1, garbage) != 1) {
        printf("%s is not a number\n", argv[1]);
        return 0;
    }
    else if(sscanf(argv[3], "%d %s", &n2, garbage) != 1) {
        printf("%s is not a number\n", argv[3]);
        return 0;
    }
    else if(sscanf(argv[2], "%c %s",  operand, garbage) != 1) {
        printf("%s is not a valid argument\n", argv[2]);
    }
    else
    {
        if(*operand == '+') {
            printf("%d + %d = %d\n", n1, n2, n1 + n2);
        }
        else if(*operand == '-') {
            printf("%d - %d = %d\n", n1, n2, n1 - n2);
        }
        else if(*operand == '*') {
            printf("%d * %d = %d\n", n1, n2, n1 * n2);
        }
        else if(*operand == '/') {
            printf("%d / %d = %d\n", n1, n2, n1 / n2);
        }

    }
}
Kelly VM
  • 45
  • 5

1 Answers1

1

I think passing the * as '*' (simple quotes) would do the trick as bash won't expand simple quoted strings.

If this is not allowed neither, you can have a look at this post on how to disable bash expansion: Stop shell wildcard character expansion?

Also, there is no way this can be done inside your program as the expansion occurs before you program is actually called.

Regards

Community
  • 1
  • 1
Eric T.
  • 76
  • 5
  • Thanks for the suggestions. Using the quotes surrounding the asterisk does produce the expected result. But like using `\*`, ' ' is not allowed. The third part of your post regarding shell expansion makes me think i have approached this problem incorrectly. – Kelly VM May 01 '16 at 08:28
  • So, misunderstanding on my part was the case. After clarification I learned that the bash script used to grade the assignments will be providing `\*` for multiplication command line argument. Your answer showed me that "Also, there is no way this can be done inside your program as the expansion occurs before you program is actually called.", so thank you! – Kelly VM May 04 '16 at 00:49