Skip to main content

C++ Program to implement Operator Overloading for String Comparison with relational op (+, , ==)


#include
#include
#include
using namespace std;

 
class CStrings{
    private:
        char str[20];
    public:
        void getdata();
        friend CStrings operator+(CStrings&, CStrings&);
        friend int operator<(CStrings&, CStrings&);
        friend int operator>(CStrings&, CStrings&);
        friend int operator==(CStrings&, CStrings&);
    };
 
void CStrings :: getdata(){
    cout<<"\n Enter a String: ";
    cin>>str;
    }
 
CStrings operator+(CStrings &s1, CStrings &s2){
    CStrings Os;
    strcpy(Os.str, s1.str);
    strcat(Os.str, s2.str);
    cout<<"\n Concatenation of Str1 & str2: "<
    return Os;
    }
 
int operator<(CStrings &s1, CStrings &s2){
    if(strcmp(s1.str, s2.str) < 0)
        return 1;
    else
        return 0;
    }
 
int operator>(CStrings &s1, CStrings &s2){
    if(strcmp(s1.str, s2.str) > 0)
        return 1;
    else
        return 0;
    }
 
 
int operator==(CStrings &s1, CStrings &s2){
    if(strcmp(s1.str, s2.str) == 0)
        return 1;
    else
        return 0;
    }
 
void main(){
    clrscr();
    CStrings Ostr, Ostr1, Ostr2;
 
    cout<<"\n Enter the Information:-"<
    Ostr1.getdata();
    Ostr2.getdata();
 
    cout<<"\n String Concatenation:-"<
    Ostr = Ostr1 + Ostr2;
 
    cout<<"\n String Comparison:-"<
    if(Ostr1 < Ostr2)
        cout<"\t str1 is less than str2";
    else if(Ostr1 > Ostr2)
        cout<"\t str1 is greater than str2";
    else if(Ostr1 == Ostr2)
        cout<"\t str1 and str2 are equal.";
 
    getch();
    }


Comments