How do I make an command line argument a variable?
That is, for example, how do I know what n(positive integer) is when user types ./a.out -n?
I know I can use strcmp(argv[1], "-1")
strcmp(argv[1], "-100")
but is there a simpler way to implement this?
You can use
strtol(argv[1])
or atoi(argv[1])
to get the integer no need to compare it as a string and see.
PS: atoi(NULL) will cause UB.
Check the code below:
int main(int argc, char **argv)
{
int n;
if( argc >2)
return 1;
if(argv[1][0] == '-')
n = atoi(argv[1] +1);
else
n= atoi(argv[1]);
printf("%d\n",n);
return 0;
}
Assuming that -n
is a command line optional argument, It is always suggested using getopt
or Argp
, and use case
to check if it its a positive integer.
Refer the following links for further information about using them http://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html
For more information about command line arguments, the following link will help you http://courses.cms.caltech.edu/cs11/material/c/mike/misc/cmdline_args.html
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.