I'll go straight to the point. This is my code, and I want to read the '*' char from command line parameter, but it's not working properly. I hope you can explain me what I'm doing wrong.
#include <stdio.h>
#include <stdlib.h>
int sum(int, int);
int rest(int, int);
int division(int, int);
int mult(int, int);
int module(int, int);
int main(int argc, char **argv){
char operator;
int number1;
int number2;
int result;
if(argc != 4){
printf("Wrong parameter quantity (%d of 3 needed)\n", argc-1);
return -1;
}
number1 = atoi(argv[1]);
operator = *argv[2];
number2 = atoi(argv[3]);
switch(operator){
case '+':
result = sum(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '-':
result = rest(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '/':
result = division(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '*':
result = mult(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
case '%':
result = module(number1, number2);
printf("%d %c %d = %d\n", number1, operator, number2, result);
break;
default:
printf("Error. Wrong operator inserted (%d, %c)\n", operator, operator);
return -2;
}
return 0;
}
int sum(number1, number2){
return number1 + number2;
}
int rest(number1, number2){
return number1 - number2;
}
int division(number1, number2){
return number1 / number2;
}
int mult(number1, number2){
return number1 * number2;
}
int module(number1, number2){
return number1 % number2;
}
I know my mistake is en this line operator = *argv[2];
but I don't know what happens when the '*' char is passed through command line parameter. For all other symbols (+, -, /, %) everything works fine. I'm coding this in Ubuntu and compiling in command line with gcc.
The problem isn't in your program. It's how you're calling it.
The UNIX/Linux shell automatically expands *
on the command line to all files in the current directory. To prevent that, you need to quote it.
So instead of doing this
./prog 3 * 4
Do this:
./prod 3 "*" 4
Or this:
./prod 3 \* 4
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.