nDARQ
nDARQ

Reputation: 9

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.

Upvotes: 0

Views: 5911

Answers (4)

Rizwan
Rizwan

Reputation: 3666

char *argv[] is a char array that makes a null terminated string, which indeed don't have overloaded == to test equality of the string. When you say == in statement argv[1] == "nomast" its actually comparing pointers.

Where in

string s1 = argv[1];
string s2 = "nomast";

s1 and s2 are string objects. Which have overloaded == to test equality.

To test equality of char string in first case use if (strcmp(argv[1], "nomast") == 0) function or you can write your own function to check equality. However today it is recommended to use standard library std::string for stings.

Upvotes: 0

AndrejH
AndrejH

Reputation: 2109

You should use strcmp() function to compare two C strings. For C++ strings you can use string::compare.

Upvotes: 1

Rerito
Rerito

Reputation: 6086

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.

Upvotes: 8

wdudzik
wdudzik

Reputation: 1334

The problem is simple, this line

 cout << (argv[1] == "nomast" ? "equal" : "not equal") << endl;

gives you not equal as you are comparing char* (pointers) and there are not equal to each other. This comparison is acutaly doing something like 0x00134 == 0x00345 both of these are under different memory adresses.

On the second case with std::strings there is special operator== which will compare you strings by characters which they contain.

To get the same result with first example you would need to do

if (strcmp(argv[1], "nomast") == 0) //need to add #include <string.h>

Upvotes: 1

Related Questions