The comparative operators
== != < <= > >=
were overloaded in the string class.
This allows you to use strings to formulate the conditions for branches and loops.
// str1 and str2 are objects of type string if( str1 < str2) // str1 is less than str2? . . .
Strings are compared lexicographically, that is character by character, beginning at the first character.
Inputs and compares lines of text.
#include <iostream> #include <string> using namespace std; string prompt = "Please enter two lines of text!\n", line( 30, '-'); int main() //from ww w. j ava2 s . c o m { string line1, line2; cout << line << '\n' << prompt << line << endl; getline( cin, line1); // Read the first getline( cin, line2); // and second line. if( line1 == line2) cout << " Both lines are the same!" << endl; else { cout << "The smaller line is:\n\t"; cout << (line1 < line2 ? line1 : line2) << endl; int len1 = line1.length(), len2 = line2.length(); if( len1 == len2) cout << "Both lines have the same length! \n"; else { cout << "The shorter line is:\n\t"; cout << (len1 < len2 ? line1 : line2) << endl; } } return 0; }