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

标签 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!");
    }
}

最佳答案

这与 C 无关,而与您的 shell 无关。如果您希望能够将它们作为参数,则需要引用 * (和其他 shell 特殊字符)。否则 shell 将进行替换,特别是 globbing。

所以你需要调用你的程序:

./myprog 3 '*' 2

关于c - 如何从 C 命令行读取星号 ( * ) 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59793369/

相关文章:

c++ - 使用串行通信 C++ 发送和接收 float

c - 避免所有系统消息和来自其他软件的消息

c++ - C++11 中具有 C 链接的复杂类型

windows - For 循环运行两次,但仅针对第一个文件

svn - TortoiseSVN 命令行差异

java - 通过命令提示符在java中制作 list 文件

c - 将字符串插值转换为 C

MPI "hello world"编译失败

linux - 管道值以退出代码

bash - Linux 命令在 shell 命令行中表现异常