getline() and write() functions

A line of text can be read or display effectively using the line oriented input/output functions getline() and write().

The getline() function reads a whole line of text that ends with a newline character.This function can be invokedby using the object cin as follows:


This function call invokes the function getline() which reads character input into the variable line.The reading is terminated as soon as either the newline character ‘\n’ is encountered or size-1 characters are read(whichever occurs first).The newline character is read but not saved.instead it is replaced by the null character.

For example consider the following code:
char name[20];

Assume that we have given the following input through key board:
Bjarne Stroustrup This input will be read correctly and assigned to the character array name. Let us suppose the input is as follows: Object Oriented Programming In this case ,the input will be terminated after reading the following 19 characters Object Oriented Pro Remember ,the two blank spaces contained in the string are also taken into account.Strings cen be read using the operator >> as follows cin>>name; But remember cin can read strings that do not contain white spaces.This means that cin can read just one word and not a series of words such as “Bjarne Stroustrup”.But it can read the following string correctly: Bjarne_Stroustrup After reading the string ,cin automatically adds the terminating null character to the character array.

The program below demonstrates the use of >> and getline() for reading the strings.


Reading Strings With getline()
 #include <iostream.h>
using namespace std; 
int main()
{ int size=20;
char city[20];
cout<<”enter city name:\n “; cin>>city;
cout<<"city name:"--- "\n\n";
cout<<"enter city name again: \n";
cout<<”city name now:” ”\n\n”;
cout<<”enter another city name: \n”;
cout <<”New city name:”--- ”\n\n’;
return 0;
output would be:
 first run
 enter city name:
 Enter city name again:
 City name now:
 Enter another city name:
 New city name: Chennai

During fist run the newline character ‘\n\ at the end of “Delhi” which is waiting in the input queue is read by the getline() that follows immediately and therefore it dos not wait for any response to the prompt ‘enter city name again’.The character’\n’ is read as an empty line.

The write() function displays an entire line and has the following form:

The first argument line represents the name of the string to be displayed and the second argument size indicates the number of characters automatically when the null character is encountered.If the size is greater than the length of line, then it displays beyond the bound of line

It is possible to concatenate two strings using the write() function.The statement
is equivalent to the following two statements: