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 "\" e.g.
./calc 2 3 4 + \*
or
./calc 2 3 4 + "*"
精彩评论