C++ comparing c string troubles

廉价感情. 提交于 2019-12-11 02:02:20

问题


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.


回答1:


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.




回答2:


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.




回答3:


This one will work fine in C. Remember to check argc so you won't get seg fault. There is also strncmp() which is a safer way to compare strings as you limit the max length of the strings.

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

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

If you are passing multiple params as command options check out getopt()



来源:https://stackoverflow.com/questions/1997778/c-comparing-c-string-troubles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!