Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ comparing c string troubles

I have written the following code which will does not work but the second snippet will when I change it.

int main( int argc, char *argv[] )
{
  if( argv[ 1 ] == "-i" )   //This is what does not work
     //Do Something
}

But if I write the code like so this will work.

int main( int argc, char *argv[] )
{
  string opti = "-i";

  if( argv[ 1 ] == opti )   //This is what does work
     //Do Something
}

Is it because the string class has == as an overloaded member and hence can perform this action?

Thanks in advance.

like image 271
user174084 Avatar asked Mar 17 '26 12:03

user174084


2 Answers

Is it because the string class has == as an overloaded member and hence can perform this action?

You are correct. Regular values of type char * do not have overloaded operators. To compare C strings,

if (strcmp(argv[1], "-i") == 0) {
    ...
}

By comparing the strings the way you did (with == directly), you are comparing the values of the pointers. Since "-i" is a compile time constant and argv[1] is something else, they will never be equal.

like image 191
Greg Hewgill Avatar answered Mar 19 '26 02:03

Greg Hewgill


Correct. When you do argv[1] == "-i" (using == on two char* expressions) you're comparing the pointers for equality, not the characters in the string. You have to use the strcmp function to compare the string data.

std::string has overloaded operators to check string==string, char*==string, and string==char*, but it's impossible to overload char*==char* since that already has a defined meaning: comparing the pointers.

like image 32
Nicolás Avatar answered Mar 19 '26 02:03

Nicolás



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!