C ++比较C字符串的麻烦 [英] C++ comparing c string troubles

查看:86
本文介绍了C ++比较C字符串的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了下面的代码,该代码将不起作用,但是当我更改它时,第二个代码段将起作用。

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?

预先感谢。

推荐答案


是因为字符串类具有==作为重载成员,因此可以执行此操作?

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

您是正确的。类型 char * 的常规值没有重载运算符。要比较C字符串,

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

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

通过比较字符串的方式(用 == 直接),您正在比较指针的。因为-i 是一个编译时间常数,而 argv [1] 是一个编译时间常数,所以它们永远不会相等

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.

这篇关于C ++比较C字符串的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆