Overloaded operators >> and <<
The operators ‘>>’ and ’<<’ are overloaded respectively in the istream and ostream class. The following is the general format of reading data from the keyboard.
Cin>>variable1>> variable2>> ......>> variablenN
The input data are separated by white spaces and should match the type of data in the cin list. Spaces and new lines will be skipped. The operator reads the data character by character and assigns it to the indicated location. The reading variable will be terminated at the encounter of a white space or a character that does not match the destination type. For example:
Int code;
Suppose the following data is given as input: 4258D
The operator will read the characters up to 8 and the value 4258 is assigned to code.
Put() and get() functions
The classes istream and ostream define two member functions get() an put() respectively to handle the single character input/output operations. We can use both types of get() functions get(char*) and get(void) prototypes to fetch character including the blank spaces, tab and the newline character. The get(char*) version assigns the input character to its argument and the get(void) version returns the input character.
Example :
Char c;
Cin.get(c);
While(c != ‘\n’)
{
cout<<>
Cin.get(c);
}
This code reads and displays a line of text (terminated by a newline character). Remember, the operator >> can also be used to read a character. The above while loop will not work properly if the statement cin>>c; is used in place of cin.get(c);
The get(void) version is used as follows:
.....
Char c;
C=cin.get; // cin.get(c) replaced
.......
The value returned by the function get() is assigned to the variable c.
The function put(), a member of ostream class, can be used to output a line of text, charater by character. For example,
Cout.put(‘x’);
Displays the character x and
cout.put(ch);
displays the value of variable ch.
Getline() and write() functions
We can read and display a line of text more efficiently using the line oriented input output functions getline() and write(). The getline() function reads a whole line of text that end s with a newline character .
Syntax: cin.getline(line,size);
Eg: char name[20];
Cin.getline(name,20);
Assume that the input was
Bjarne stroustrup
This input will be read correctly and assigned to the character array name. Let us suppose the input was : object oriented programming
In this the input will be terminated after reading the first 19 characters.
The write() function displays an entire line and has the following form:
Cout.write(line,size)
The first argument line represents the name of the string to be displayed and the second argument size indicates the number of characters to display. Note that it does not stop dislaying the charaters 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.
No comments:
Post a Comment