C command line argument check
Solution 1
First of all, to check if there is an argument, you should use the argc variable of the main(int argc, char** argv)
, which indicates the length of your argv array.
if (argc < 3) {
printf("missing argument\n");
exit(-1);
}
As for strcmp
, the man page only states that it returns 0 if the two strings in argument are equal, else non-zero... but not necessarily 1. In fact it is implementation dependent. The way to use it to check for string equality is therefore :
if (0 == strcmp(argv[2], "on")) {
// do something
} else {
// do something else
}
Solution 2
If your program is something like this
#include <stdio.h>
int main (int argc, char**argv)
{
if (argc >= 3 && strcmp (argv[2],"on") == 1){
// STACKprint();
printf("\n");
}
}
and you try to run it with myexe 1 on
, It will never go into the if block
and if you change the 1 to 0, it will go.
Something else is wrong.
It will be nice if you can post your code and the way you are calling it.
apot
Updated on July 30, 2020Comments
-
apot almost 4 years
I have the below part of code in which I noticed that if I change the 0 to 1 the result is the same. I get the
STACKprint();
with "on" as the second argument, nothing with anything else and if there is no argument I get a segmentation fault. I guess for the segmentation fault I need to check if the argument isNULL
but I am not sure how to do that with the second parameter and it really bugs me out why(strcmp (argv[2],"on") == 1)
has no effect. Is it not supposed to take a TRUE value?if (strcmp (argv[2],"on") == 0) { STACKprint(); printf("\n"); }
-
chux - Reinstate Monica almost 9 yearsSure you want
strcmp (argv[2],"on") == 1
instead ofstrcmp (argv[2],"on") == 0
orstrcmp (argv[2],"on") != 0
? -
Jay almost 9 yearsYou mean
argc<3
, since he's usingargv[2]
, right? -
goodfellow over 3 yearsGood point @chux. This is not going to work as expected (programiz.com/c-programming/library-function/string.h/strcmp0