C ++相同的字符串不相等(实际上是char *) [英] c++ same strings not equal (char* actually)

查看:43
本文介绍了C ++相同的字符串不相等(实际上是char *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将参数传递到程序中时遇到问题,除了它们是相同的以外,似乎不等于我输入的参数.将它们转换为字符串会使它们完全相同,但是我想知道为什么最初的二重奏组不是这样.

I have a problem with passing an argument into my program, seems to not be equal to what I put in as argument, except they're identical. Turning them into a string makes them identical, but I would like to know why the initial duo isn't.

这是我的代码:

int main(int argc, char *argv[]) {
  if (argc>1) {
    cout << "#" << argv[1] << "#" << endl;
    cout << "#" << "nomast" << "#" << endl;
    cout << (argv[1] == "nomast" ? "equal" : "not equal") << endl;

    string s1 = argv[1];
    string s2 = "nomast";
    cout << (s1 == s2 ? "equal after all" : "nope") << endl;
    system("pause");
  }
  return 0;
}

当我使用"call somethingy.exe nomast"启动编译后的代码时,会得到输出

When I launch the compiled code with "call thingy.exe nomast" I get the output

#nomast#
#nomast#
not equal
equal after all
Press any key to continue . . .

我最好的主意是我没有正确处理"char * argv []".不过,不知道该如何处理.

My best idea is that I'm not handling the "char *argv[]" properly. Don't know how to handle it differently though.

推荐答案

您正在比较指针(换句话说就是地址),而不是它们的内容.由于您使用的是C ++,因此建议您使用 std :: string 并比较这些对象(就像您在第二次比较中所做的那样).

You are comparing pointers, in other word addresses, not their content. Since you are using C++ I suggest you use std::string and compare such objects instead (as you did in your second comparison).

否则,如果必须使用C,只需使用C标准库中的 strcmp 函数.

Otherwise, if you have to deal with C, just use the strcmp function from the C standard library.

这篇关于C ++相同的字符串不相等(实际上是char *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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