<分区>
我编写了一个代码来执行从命令行获取输入的简单算术运算。所以如果我想做乘法,我会在终端中输入“prog_name 2 * 3”,它应该输出“Product : 6”。
问题是,除乘法外,所有运算都有效。经过一些测试,我发现用于获取运算符的第三个参数(argc[2])实际上存储的是程序名称。那么我怎样才能使这项工作呢?
这是代码:
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
int a, b;
if(argc != 4)
{
printf("Invalid arguments!");
system("pause");
exit(0);
}
a = atoi(argv[1]);
b = atoi(argv[3]);
switch(*argv[2])
{
case '+':
printf("\n Sum : %d", a+b);
break;
case '-':
printf("\n Difference : %d", a-b);
break;
case '*':
printf("\n Product : %d", a*b);
break;
case '/':
printf("\n Quotient : %d", a/b);
break;
case '%':
printf("\n Remainder: %d", a%b);
break;
default:
printf("\n Invalid operator!");
}
}