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
Printable View
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
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.
That code doesn't compare addresses, it compares the second character in both strings. You know that [] dereference pointers, do you?
Easier way IMHO is to use string class
Code:#include <string>
int main(void)
{
string Str1("hello");
string Str2("hello");
if (Str1 == Str2)
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.