Thursday, November 23, 2017

C++ Code Review: Using Operator overload to compare two strings for equality.

Description: This program uses operator overload to compare two strings for equality.

Code:

//Compiling Tool: Code::Block IDE with MinGW

//Program compares two strings & tells whether equal or not.

 

#include<iostream>

#include<stdio.h> //used for gets()

#include<string.h> //used for strcmp()

 

using namespace std;

 

class String

{

    char str[20];

public:

    void

    getdata()  //function to read the string

    {

        gets(str);

    }

 

    //operator fun:overload comparison operator for compare two strings

 

    int operator

    ==(String s)

    {

        if(!strcmp(str,s.str))

            return 1;

        return 0;

    }

};

 

int main()

{

    String s1,s2;

 

    cout<<"Enter first string:";

    s1.getdata();

 

    cout<<"Enter second string:";

    s2.getdata();

 

    if(s1==s2) //here the operator function will be called

    {

        cout<<"Strings are Equal";

    }

    else

    {

       cout<<"Strings are Not Equal";

    }

 

    return(0);

}       

 

Output:

 clip_image002

If you want to write or construct or program C++ mini-project and do not know how or from where to start buy this simple e-book: Code Review of 26 C++ mini-projects. For book sample click this link.

Add your comments in below available comment box.

Note: Click these label/tags to view all related posts. Tags: C++Code

 

…till next post, bye-bye & take care.

No comments:

Post a Comment