Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Comparing char arrays
Index -> Programming, C++ -> C++ Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Martin




PostPosted: 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?
Sponsor
Sponsor
Sponsor
sponsor
octopi




PostPosted: Sun Jun 15, 2003 5:47 pm   Post subject: (No 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.)
Display posts from previous:   
   Index -> Programming, C++ -> C++ Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: