Pages

100 Contemporary Living Room Designs

Tuesday, September 18, 2012

C++ PROGRAM TO CREATE A CLASS CALLED STRING.

Write a C++ program to create a class called STRING and implement the following operations. Display the results after every operation by overloading the operator.
 
STRING s1 = “HELLO”

STRING s2 = “WORLD”

STIRNG s3 = s1 + s2 ; (Use copy constructor).

 
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
  char name[23];
  public :string()
  {
    name[23]='\0';
  }
  string(char s[])
  {
    strcpy(name,s);
  }
  string(string &s)
  {
    strcpy(name,s.name);
  }
friend string operator +(string s1, string s2);
friend ostream &operator <<(ostream  &out, string &s);
};
ostream &operator <<(ostream &out , string &s)
{
  out <<"\t"<<s.name<<endl;
  return(out);
}
string operator +(string s1, string s2)
{
  string temp(s1);
//strcat(temp.name,"");
  strcat(temp.name, s2.name);
  return(temp);
}
void main()
{
  clrscr();
  string s1("hello ");
  string s2("world");
  string s3=s1+s2;
  cout<<"\nFIRST STRING ="<<s1
      <<"\nSECOND STRING ="<<s2;
  cout<<"\nCONCATENATED THIRD STRING ="<<s3;
  getch();
}


OUTPUT


1 comment:

  1. Can someone please explain what this line does
    out<<"\t"<<s.name<<endl;

    ReplyDelete