Creating string object in C++

Creating string object :- To prepare any string object following three types of constructors are used in string class.User can prepare string object by using one of the following statements –
A. string s1;
B. string s2 (“Ajay”);
C. string s3(s2);
                Or
          string s3;
            s3=s2;
D. string s4=s2+ “ ”+ “Rathod”;
E. cout << “enter a string”<<endl;
cin>>s1;
F. getline ( cin, s1);

Here + sign is used to concatenate two strings. This work is also done by += operator
e.g. s4=s4+s2; or s4+=s2;

Operator left shift  (<<) and operator right shift  (>>) are used to send output and receive/access input from console.
cout<<s1;
cin>>s1;

C++ program for creating string objects.

#include<iostream.h>
#include<conio.h>
#include<string.h>
int main(){
string s1;
cout<<Enter a string "<<endl;
cin>>s1; //s1=Raja
string s2("Rammohan");
string s3=s1+" "+s2+" "+"Rai";
string s4="Jii";
string s3+=s4;
cout<<"Strings are..."<<endl;
cout<<"S1="<<s1<<endl<<"S2="<<s2<<endl<<"S3="<<s3<<endl<<"S4="<<s4<<endl;
getch();
return1;
}

No comments:

Post a Comment