Comparing string objects - C++ Data Type

C++ examples for Data Type:string

Description

Comparing string objects

Demo Code

#include <iostream>
#include <string>
using namespace std;
int main()//from   w  w w.j a va 2 s . c om
{
   string aName = "George";
   string userName;
   cout << "Enter your first name: ";
   cin >> userName;
   if(userName==aName)
      cout << "Greetings, George\n";
   else if(userName < aName)
       cout << "You come before George\n";
   else
      cout << "You come after George\n";
   int n = userName.compare(0, 2, aName, 0, 2);
   cout << "The first two letters of your name ";
   if(n==0)
         cout << "match ";
   else if(n < 0)
      cout << "come before ";
   else
         cout << "come after ";
   cout << aName.substr(0, 2) << endl;
   return 0;
}

Result


Related Tutorials