Thread: ? comparing elements of a char array

  1. #1
    Unregistered
    Guest

    ? comparing elements of a char array

    How can I compare 2 elements in a char array?

    This doesn't seem to work:

    char word1 [5] = "asdf";
    char word2 [5] = "aser";

    if(word1[1] == word2[1])
    {
    cout << "match";
    }

    Thanks

  2. #2
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    you have to use the strcmp() function (found in <string.h>) to compare strings. otherwise it compares addresses which is probably not what you want.
    If a tree falls in the forest, and no one is around to see it, do the other trees make fun of it?

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    164
    That code doesn't compare addresses, it compares the second character in both strings. You know that [] dereference pointers, do you?
    // Gliptic

  4. #4
    Registered User kitten's Avatar
    Join Date
    Aug 2001
    Posts
    109
    Easier way IMHO is to use string class

    Code:
    #include <string>
    
    int main(void)
    {
    string Str1("hello");
    string Str2("hello");
    
    if (Str1 == Str2)
    Making error is human, but for messing things thoroughly it takes a computer

  5. #5
    Fingerstyle Guitarist taylorguitarman's Avatar
    Join Date
    Aug 2001
    Posts
    564
    Sorry, I wasn't paying attention. I didn't even see the array indexes were there. I just assumed they were trying to compare char strings with the == operator.

    It worked just fine for me.

    again, sorry to insult your intelligence.
    Last edited by taylorguitarman; 09-20-2001 at 07:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-17-2008, 12:36 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Passing structures... I can't get it right.
    By j0hnb in forum C Programming
    Replies: 6
    Last Post: 01-26-2003, 11:55 AM
  4. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 01:18 AM