tags:

views:

140

answers:

4

I am trying to compare the parameter of command with argv[] but it's not working. Here is my code.

./a.out -d 1

In main function

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

if (argv[1] == "-d")

    // call some function here

}

But this is not working... I don't know why this comparison is not working.

A: 

won't that be if (argv[0] == "-d")

0 not 1?

Viper_Sb
No, because the first element of `argv` is the program name.
Adrian
no, C and C++ have char[] for character strings like this; it turns into a pointer comparison
Paul Nathan
Nop. First, you are comparing addresses, not contents. Second, argv[0] is the command path.
ninjalj
+12  A: 

You can't compare strings using ==. Instead, use strcmp.

#include <string.h>

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

if (strcmp(argv[1], "-d") == 0)

// call some function here

}

The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify "-d" in your code, it makes a whole new string in memory. Since the location of the new string and argv[1] aren't the same, == will return 0.

Adrian
You may want to mention that the reason C strings can't be compared is because it doesn't compare the contents, just the pointers.
Cristián Romo
or if you know your args are single letters (argv[1][1] =='d')
Martin Beckett
@Cristian: I edited, thanks for pointing that out.
Adrian
@Mark: No, because `argv[1][0] == '-'`.
Adrian
Thanks for your answer. It is working.
itsaboutcode
@Martin: It is just a sample input, which means it can have more than 1 letter, but your suggestion is very good.
itsaboutcode
@itsaboutcode - thats why unix commands traditionally had single letter options
Martin Beckett
+2  A: 

You may want to use strcmp here.

Brandon Horsley
+2  A: 

In C++ let std::string do the work for you:

#include <string>
int main (int argc, char * const argv[]) {

if (argv[1] == std::string("-d"))

// call some function here

}

In C you'll have to use strcmp:

if (strcmp(argv[1], "-d") == 0)

// call some function here

}
Mark B