char[] comparison

Apr 20, 2008 at 12:47pm
Hello,
How do I compare the values stored in char arrays?
Any assistance will be appreciated. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
char name[ 50 ];
char address[ 50 ];

char search4This[ 50 ];

cout << "Enter your name";
cin.getline( name, 50 );

cout << "Enter your address: ";
cin.getline( address, 50 );

cout << "\n\nWhat name or address would you like to find? ";
cin.getline ( search4This, 50 );

 if ( name == search4This || address == search4This )
     cout << "Found it";
  else
     cout << "No such information exists";
                            
 }// end main                            
Last edited on Apr 20, 2008 at 12:52pm
Apr 20, 2008 at 1:15pm
1
2
3
4
5
6
7
8
9
#include <cstring>
...
//strcmp() returns a 0 if the two strings are equal,
//  a 1 if the first string is greater than the second (ASCII value comparison),
//  and a -1 if the first string is less than the second

strcmp("hello", "hello"); //0
strcmp("hello", "bellow"); //1
strcmp("bellow", "hello"); //-1 

If you notice, strcmp() doesn't care about the length of the string; it only cares about how each value in one string compares with the corresponding value in the other string.

I hope this helps! ^_^

rpgfan
Apr 20, 2008 at 1:41pm
rpgfan3233,
It worked!Thank you very much for your help.
Topic archived. No new replies allowed.