我会直截了当地说。这是我的代码,我想阅读' *'来自命令行参数的char,但它无法正常工作。我希望你能解释一下我做错了什么。
#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;
}
我知道我的错误就在这一行operator = *argv[2];
但我不知道当&#39; *&#39; char通过命令行参数传递。对于所有其他符号(+, - ,/,%)一切正常。我在Ubuntu中对此进行编码,并使用gcc在命令行中进行编译。
答案 0 :(得分:5)
问题不在你的程序中。这就是你如何称呼它。
UNIX / Linux shell自动将命令行上的*
扩展到当前目录中的所有文件。为了防止这种情况,你需要引用它。
所以不要这样做
./prog 3 * 4
这样做:
./prod 3 "*" 4
或者这个:
./prod 3 \* 4