【问题标题】:How to read asterisk( * ) as an argument from the command line in C [duplicate]如何从 C 中的命令行读取星号(*)作为参数 [重复]
【发布时间】:2015-06-02 15:04:56
【问题描述】:

我编写了一个代码来执行从命令行获取输入的简单算术运算。所以如果我想做一个乘法,我会在终端中输入“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!");
    }
}

【问题讨论】:

  • 这个问题已经在两天前被问过了,而且有很多骗子!
  • 你不使用 x 进行乘法吗?这只是性格问题:-)
  • @ Yasir 我曾想过,但我只是想知道为什么 * 不起作用。我实际上在发布之前搜索了很多,但没有找到任何相关内容。

标签: c command-line


【解决方案1】:

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

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

./myprog 3 '*' 2

【讨论】:

    【解决方案2】:

    实际上,是操作系统负责扩展通配符,所以它是操作系统特定的(C 程序只接收操作系统解释的内容)。

    也就是说,在大多数操作系统中,如果您引用通配符,它​​将不会扩展 program_name 2 "*" 3。更好的是,将整个表达式作为单个参数传递 (program_name "2 * 3")

    【讨论】:

    • 不是操作系统。这是外壳。
    【解决方案3】:

    您的问题不在您的代码中。它在操作系统/外壳中。你看,命令行中的* 扩展为目录内容,所以参数2 * 3 扩展为2 dir1 dir2 file1, file2, etc...

    我建议你使用像“2*3”这样的东西作为参数和像sscanf(argv[1], "%d%c%d", &amp;a, &amp;command, &amp;b);这样的东西

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      相关资源
      最近更新 更多