C ++ comparing chain problems

I wrote the following code that will not work, but the second snippet will be 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 so that it works.

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 element and therefore can perform this action?

Thanks in advance.

+2
source share
3 answers

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

You're right. Ordinary type values char *do not have overloaded operators. To compare the strings of C,

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

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

+11

. argv[1] == "-i" ( == char*), , . strcmp.

std::string == string, char * == string == char *, char * == char *, : .

+9

C. argc, seg. strncmp(), .

#include <string.h>
#include <stdio.h>

int main( int argc, char *argv[] )
{
  if((argc > 1) && (strcmp(argv[1], "-i") == 0))
  {
      printf("got -i\n");
  }
}

, getopt()

+1

Source: https://habr.com/ru/post/1737504/


All Articles