Reading Strings in C++

Method 1 :
------------
#include
void main(void)
{
char *name;

cout<<"\n Enter any name : ";
cin>> name;

cout <<" \n Name is : "<<*name;
}

In method 1, we are using cin to read string, which gets terminated space or carriage return occurs. When more than one word is entered with space between words cin considers only the first word and all remaining input is discarded.

Method 2:
------------
#include
void main(void)
{
char *name;

cout<<"\n Enter any name : ";
cin.getline(name,100);

cout <<" \n Name is : "<<*name;
}

In method 2, we are using getline() function of cin object which gets terminated when carriage return(\n) occurs hence it accepts more than one word with space. In the syntax of getline() function 100 is specified which indicates how many maximum characters it can accept. This number can be varied. 


Comments