如何从C的命令行读取星号(*)作为参数

Elb*_*ben 0 c command-line

我已经编写了一个代码来执行简单的算术运算,并从命令行获取输入。因此,如果要进行乘法运算,可以在终端中键入“ 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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 5

这与C无关,但与您的shell无关。*如果希望能够将它们用作参数,则需要引用(和其他shell特殊字符)。否则,壳将被取代,尤其是球化。

因此,您需要使用以下命令调用程序:

./myprog 3 '*' 2
Run Code Online (Sandbox Code Playgroud)