Computer Science Canada

Comparing char arrays

Author:  Martin [ Sun Jun 15, 2003 5:00 pm ]
Post subject:  Comparing char arrays

This is my code:
code:
#include <iostream.h>

int main()
{
        char n1 [10] = "HELLO";
        char n2 [10] = "HELLO";
        if (n1==n2)
        {
                cout <<1;
        }
        else
        {
                cout << 0;
        }
        return 0;
}


Why is the output 0?

Author:  octopi [ Sun Jun 15, 2003 5:47 pm ]
Post subject: 

When you compare strings the way you have shown, I belive it compares their pointers, and not the acctual data, that is why you get the undesired result.

You should use strcmp();

code:
#include <iostream.h>
#include <string>

int main()
{

   char n1 [10] = "HELLO";
   char n2 [10] = "HELLO";
   if (strcmp(n1,n2) == 0)  {
      cout << "match\n";
   }
   else {
      cout << "don't match\n";
   }


   std::string an1 = "HELLO";
   std::string an2 = "HELLO";
   if (an1 == an2)  {
      cout << "match\n";
   }
   else {
      cout << "don't match\n";
   }
   return 0;
}


You could of course use std::string to do what you want. (As shown above.)


: