How to read asterisk( * ) as an argument from the

2020-02-06 17:48发布

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".

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?

This is the code:

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

3条回答
在下西门庆
2楼-- · 2020-02-06 18:19

Actually, it is the OS the one in charge of expanding the wildcards, so it is OS-specific (the C program receives just what the OS has interpreted).

That said, in most OS if you quote the wildcard it will not be expanded program_name 2 "*" 3. Even better, pass the whole expression as a single parameter (program_name "2 * 3")

查看更多
等我变得足够好
3楼-- · 2020-02-06 18:25

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
查看更多
再贱就再见
4楼-- · 2020-02-06 18:33

Your problem is not in your code. It is in the OS/shell. You see, the * in the command line expands to the directory contents so the arguments 2 * 3 expands to 2 dir1 dir2 file1, file2, etc...

I suggest you to use someting like "2*3" as an argument and something like sscanf(argv[1], "%d%c%d", &a, &command, &b);

查看更多
登录 后发表回答