简体   繁体   中英

How to get the correct number of C++ command line arguments?

I start my program with

int main (int argc, char *argv[]) {
    printf("%d \n", argc);

then I compiled in Ubuntu using g++, and I ran the program using

./calc 2 3 4 + *

but the program outputs 17! I did a printf on the arguments as well, they are:

arg 0: ./calc 
arg 1: 2 
arg 2: 3 
arg 3: 4 
arg 4: + 
arg 5: 1.2.c 
arg 6: 1.3.c 
arg 7: 1.4.c 
arg 8: 2.1.c 
arg 9: 2.2.c 
arg 10: 2.3.c 
arg 11: 2.4.c 
arg 12: 3.2.c 
arg 13: 3.4.c 
arg 14: 4.1.c 
arg 15: a.out 
arg 16: calc 

but obviously that's not what I'm expecting. How can I correct this?

The * is being evaluated by your shell to mean all of the files in the current directory. You should escape the asterisk using \\* .

The linux shell interpreted * as a listing of all the files in a directory. Try escaping it with "\\" eg

./calc 2 3 4 + \*

or

./calc 2 3 4 + "*"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM