C++ strings can be compared like ints:
Code:
string a = "something";
string b = "something else";
if ( a < b ) {
cout << "a is smaller\n";
} else if ( a == b ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}
C strings can't, and you have to treat them like arrays of characters:
Code:
int compareTo( char a[], char b[] ) {
for ( int i = 0; a[i] && b[i] && a[i] == b[i]; i++ );
if ( a[i] == '\0' ) {
return -1;
} else if ( b[i] == '\0' ) {
return 1;
} else {
return a[i] - b[i];
}
}
int rc = compareTo( a, b );
if ( rc < 0 ) {
cout << "a is smaller\n";
} else if ( rc == 0 ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}
Or use strcmp from string.h since it does the work for you:
Code:
int rc = strcmp( a, b );
if ( rc < 0 ) {
cout << "a is smaller\n";
} else if ( rc == 0 ) {
cout << "a and b are the same\n";
} else {
cout << "b is smaller\n";
}