小编Elb*_*ben的帖子

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

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

c command-line

0
推荐指数
1
解决办法
907
查看次数

标签 统计

c ×1

command-line ×1