Explain in detail I/O streams along with an example program

Estudies4you
4.3. Stream I/O
Q17. Explain in detail I/O streams along with an example program.
Answer:
1/O Stream
I/O streams are used to perform input and output operations on the program. I/O streams include two types of streams.
They are as follows,
(a) Input stream
(b) Output stream.

(a) Input Stream
The input stream is used to read input through standard input device, keyboard. It uses a predefined stream object cin to perform the console read operation.
The cin object uses extraction operator (>>) to perform the input operation and this operator is stored in istream class.
Syntax
cin>> variable_name;
Example
char varl;
float var2;
int var3;
cin>> varl >> var2 >> var3;

Here varl, var2, var3 are different variables declared with different datatype. After the execution of declarative statements, memory is allocated for every variable. When cin statement is executed, input stream requests for the input. If the input is N 10.0 30, then the char value N is assigned to the variable var, the float value 10.0 is assigned to var2 and the int value 30 is assigned to var3. 
If the given input is greater than the size of corresponding data type, the input remains in input stream. The data value of every variable is accepted through extraction operator >>. This operators reads the data values and stores the value in memory locations of that respective variable.

Cascading Input Operations
Cascading input operation is an input operation that allows more than one variable to read- input data. And, each variable in cin statement uses extraction operator. These variables must be separated with space, tab or enter.

(b) Output Streams
The output stream is used to control the output through standard output devices, monitor. It uses a predefined stream object cout to display the output. The cout object use insertion operator << to perform the console write operation and this operator is stored in ostream class.

Syntax
cout <<“output statement”;
cout << variable_name;

Example
cout <<“Hello world”;
cout<<varl, var2, .......;
Where, varl, var2, ....... are variables.
In the above example, the first ‘cout’ statement displays the same text “Hello world” on to the screen. The second ‘cout’ statement displays the corresponding values of the variables varl, var2, ......

Program
#include <iostream.h>
#inelude <conio.h>
int main()
{
char stdId[10];
char stdName[20];
clrscr();
cout <<Enter student id” <<endl;
cin >> stdId;.
cout <<“Student ID is:” <<stdId;
cout <<endl; //breaks the line
cout <<“Enter student name:”;
cin >> stdName;
cout <<“Student name is:” << stdName;
getch();
return 0;

Output
Enter student id:SOGC0225
Student Id is : SOGC0225
Enter student name : Nymisha
Student name is : Nymisha
While reading string values, unwanted blanks spaces between characters are not allowed. In C++, format specifiers such as %f, %d, %u are not required.


To Top