Trying to get an asterisk * as input to main from

2019-08-10 06:06发布

I'm trying to send input from the command line to my main function. The input is then sent to the functions checkNum etc.

int main(int argc, char *argv[])
{

    int x = checkNum(argv[1]);
    int y = checkNum(argv[3]);
    int o = checkOP(argv[2]);
    …
}

It is supposed to be a calculator so for example in the command line when I write:

program.exe 4 + 2

and it will give me the answer 6 (code for this is not included).

The problem is when I want to multiply and I type for example

program.exe 3 * 4

It seems like it creates a pointer (or something, not quite sure) instead of giving me the char pointer to the char '*'.

The question is can I get the input '*' to behave the same way as when I type '+'?

Edit: Writing "*" in the command line works. Is there a way where I only need to type *?

The code is running on Windows, which seems to be part of the problem.

3条回答
别忘想泡老子
2楼-- · 2019-08-10 06:17

How the shell handles the command-line arguments is outside the scope and control of your program. There is nothing you can put in the program to tell the shell to avoid performing any of its normal command-handling behavior.

I suggest, however, that instead of relying on the shell for word splitting, you make your program expect the whole expression as a single argument, and for it to parse the expression. That will not relieve you of the need for quotes, but it will make the resulting commands look more natural:

program.exe 3+4
program.exe "3 + 4"
program.exe "4*5"

That will also help if you expand your program to handle more complex expressions, such as those containing parentheses (which are also significant to the shell).

查看更多
冷血范
3楼-- · 2019-08-10 06:27

You can turn off the shell globbing if you don't want to use single quote (') or double quote (").

Do

# set -o noglob 

or

# set -f 

(both are equivalent).

to turn off the shell globbing. Now, the shell won't expand any globs, including *.

查看更多
闹够了就滚
4楼-- · 2019-08-10 06:30

As @JohnBollinger wrote in the comments, you should use

/path/to/program 3 '*' 4

the way it's written at the moment.

But some explanation is clearly required. This is because the shell will parse the command line before passing it to your program. * will expand to any file in the directory (UNIX) or something similar (windows), space separated. This is not what you need. You cannot fix it within your program as it will be too late. (On UNIX you can ensure you are in an empty directory but that probably doesn't help).

Another way around this is to quote the entire argument (and rewrite you program appropriately), i.e.

/path/to/program '3 * 4'

in which case you would need to use strtok_r or strsep to step through the (single) argument passed, separating it on the space(s).

查看更多
登录 后发表回答