To perform string concatination & string comparison using operator overloading

Write a C++ program that overloads the + operator and relational operators (suitable) to perform the following operations:

  1. Concatenation of two strings.

2. Comparison of two strings.

 

#include<iostream>
#include<string.h>
using namespace std;
class con
{
    char str1[50],str2[20];
public:
    void getdata()
    {
        cout<<"Enter the two strings"<<endl;
        cin>>str1;
        cin>>str2;
    }
    con operator +(con b)
    {
        strcat(b.str1,b.str2);
        return b;
    }
    void display()
    {
        cout<<str1<<endl;
    }
    con operator ==(con b)
    {
        if(strcmp(b.str1,b.str2)==0)
        {
            cout<<"Equal";
        }
     else
     {
         cout<<"Not Equal";
     }
    }
};
int main()
{
    con a,b,c;
    b.getdata();
    b=a+(b);
    b.display();
    b=a==(b);
}

 

2 thoughts on “To perform string concatination & string comparison using operator overloading”

  1. I think the right code should be as below:

    #include
    #include
    #include
    #include
    using namespace std;
    class con
    {
    char str1[20],str2[20];
    public:
    void getdata()
    {
    cout<<"Enter the two strings"<>str1;
    cin>>str2;
    }
    con operator +(con b)
    {
    strcat(b.str1,b.str2);
    return b;
    }
    void display()
    {
    cout<<str1<<endl;
    }
    con operator ==(con b)
    {
    if(strcmp(b.str1, b.str2) == 0)
    {
    cout<<"Equal";
    }
    else
    {
    cout<<"Not Equal";
    }
    }
    };
    int main()
    {
    con a,b,c;
    b.getdata();
    c=a+(b);
    c.display();
    b=a==(b);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *