//Program : Part B-3
//Write a program to accept two strings and using operator overloading perform //the following .
//a) Concatenation of two strings
//b) Comparison of two strings alphabetically.
//(Note : For concatenation(+), for comparison (==,>,<))
//Name : LDK E-NOTES Reg.No. : **********
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<iomanip.h>
class string
{
char st[20];
public:
void accept();
void display();
string operator+(string s);
int operator==(string s);
int operator>(string s);
int operator<(string s);
};
void string::accept()
{
cin>>st;
}
void string::display()
{
cout<<st<<endl;
}
string string::operator+(string s)
{
string a;
strcpy(a.st,st);
strcat(a.st,s.st);
return a;
}
int string::operator==(string s)
{
if(strcmp(st,s.st)==0)
return 1;
else
return 0;
}
int string::operator>(string s)
{
if(strcmp(st,s.st)>0)
return 1;
else
return 0;
}
int string::operator<(string s)
{
if(strcmp(st,s.st)<0)
return 1;
else
return 0;
}
void main()
{
string s1,s2,s3;
clrscr();
cout<<"Enter the first string : ";
s1.accept();
cout<<"Enter the second string : ";
s2.accept();
cout<<"First string = ";
s1.display();
cout<<"Second string = ";
s2.display();
int ch=1;
while(ch<=3)
{
cout<<"1.Concatenation"<<endl;
cout<<"2.Comparison"<<endl;
cout<<"3.Exit"<<endl;
cout<<"Enter your choice : ";
cin>>ch;
switch(ch)
{
case 1 : s3=s1+s2;
cout<<"Concatenation of two strings = ";
s3.display();
break;
case 2 : if(s1==s2)
cout<<"Both strings are equal"<<endl;
else
cout<<"Both strings are not equal"<<endl;
if(s1>s2)
cout<<"First string is greater than second string"<<endl;
else if(s1<s2)
cout<<"First string is less than second string"<<endl;
break;
case 3 : exit(0);
default : cout<<"Invalid choice...";
}
getch();
}
}
Output 1 :
Enter the first string : SDM
Enter the second string : CBM
First string = SDM
Second string = CBM
1.Concatenation
2.Comparison
3.Exit
Enter your choice : 1
Concatenation of two strings = SDMCBM
1. Concatenation
2. Comparison
3. Exit
Enter your choice : 2
Both strings are not equal
First string is greater than second string
Output 2 :
Enter the first string : CBM
Enter the second string : SDM
First string = CBM
Second string = SDM
1.Concatenation
2.Comparison
3.Exit
Enter your choice : 1
Concatenation of two strings = CBMSDM
1.Concatenation
2.Comparison
3.Exit
Enter your choice : 2
Both strings are not equal
First string is less than second string
Output 3 :
Enter the first string : SDM
Enter the second string : SDM
First string = SDM
Second string = SDM
1.Concatenation
2.Comparison
3.Exit
Enter your choice : 1
Concatenation of two strings = SDMSDM
1.Concatenation
2.Comparison
3.Exit
Enter your choice : 2
Both strings are equal
No comments:
Post a Comment