Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

pointers - c++ same strings not equal (char* actually)

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.

Here's my code:

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;
}

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 . . .

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...