Archive
Archive for January 19, 2010
C++ Program to implement Operator Overloading (>>, <<) – Q19
January 19, 2010
Leave a comment
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.
Categories: Cpp
Cpp, Operator Overloading




