Advertisements
Home > Cpp > C++ Program to implement Operator Overloading (>>, <<) – Q19

C++ Program to implement Operator Overloading (>>, <<) – Q19


Q19. Program to implement Operator Overloading (>>, <<):

Write a class which contains a string as private data member. Add a member function IsPalindrome that returns TRUE/FALSE depending upon whether the str is palindrome or not. Overload the <> operator to insert the string and print the string respectively along with appropriate message.

… from College notes (BCA/MCA assignments):

#include <iostream.h>
#include <string.h>
#include <conio.h>

enum bool {false, true};

class Cpal{
	private:
		char *str;
	public:
		Cpal(){}

		bool IsPalindrome();

		friend ostream& operator<<(ostream &, const Cpal &);

		friend istream& operator>>(istream &, const Cpal &);
	};

bool Cpal :: IsPalindrome(){
	int len, i, j;
	bool valid;

	len = strlen(str);

	for(i=0, j=len-1; i<len/2; i++, j--){
		if(str[i] == str[j])
			valid = true;
		else{
			valid = false;
			break;
			}
		}
	return valid;
	}

istream& operator>>(istream &istr, const Cpal &Opal){
	return istr.get(Opal.str, 80);
	}

ostream& operator<<(ostream &ostr, const Cpal &Opal){
	return ostr<<Opal.str;
	}

void main(){
	Cpal Opal;
	clrscr();

	cout<<"\n Enter a String: ";
	cin>>Opal;

	cout<<"\n The String: ";
	cout<<Opal;

	if(Opal.IsPalindrome())
		cout<<"\n\t is a Palindrome.";
	else
		cout<<"\n\t is not a Palindrome.";

	getch();
	}

 

Output:

Enter a String: able was i i saw elba

The String: able was i i saw elba
is a Palindrome.

 

Enter a String: my name is Manoj

The String: my name is Manoj
is not a Palindrome.


Advertisements
Categories: Cpp Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: