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);
}
}
}