? comparing elements of a char array

This is a discussion on ? comparing elements of a char array within the C++ Programming forums, part of the General Programming Boards category; How can I compare 2 elements in a char array? This doesn't seem to work: char word1 [5] = "asdf"; ...

  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 08: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, 08: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21