如何从C的命令行中将asterisk

如何从C的命令行中将asterisk

本文介绍了如何从C的命令行中将asterisk(*)作为参数读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码来执行简单的算术运算,并从命令行获取输入.因此,如果要进行乘法运算,可以在终端中键入"prog_name 2 * 3",该终端应输出"Product:6".

I have written a code to do simple arithmetic operations which gets input from the command line. So if I wanted to do a multiplication, I would type "prog_name 2 * 3" in the terminal, which should output "Product : 6".

问题是,除乘法外,所有运算都有效.经过一些测试,我发现用于获取运算符的第三个参数(argc [2])实际上是在存储程序名称.那么我该如何做呢?

The problem is, all the operations work except the multiplication. After some testing, I found that the third argument(argc[2]),which is used to get the operator, is actually storing the program name. So how can I make this work?

这是代码:

#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特殊字符).否则,壳会被取代,尤其是球化.

This has nothing to do with C but with your shell. You need to quote * (and other shell special characters) if you want to be able to take them as argument. Otherwise the shell will to substiutions, in particular globbing.

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

So you need to call your program with:

./myprog 3 '*' 2

这篇关于如何从C的命令行中将asterisk(*)作为参数读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:41