|
Page 1 of 2
C++ Standard Input Output Stream
In this C++ tutorial, you will learn about standard input stream and standard output stream explained along with syntax and examples.
C++ programming language uses the concept of streams to perform input and output operations using the keyboard and to display information on the monitor of the computer.
What is a Stream?
A stream is an object where a program can either insert or extract characters to or from it. The standard input and output stream objects of C++ are declared in the header file iostream.
Standard Input Stream
Generally, the device used for input is the keyboard. For inputting, the keyword cin is used, which is an object. The overloaded operator of extraction, >>, is used on the standard input stream, in this case: cin stream. Syntax for using the standard input stream is cin followed by the operator >> followed by the variable that stores the data extracted from the stream.
For example:
int prog;
cin >> prog;
In the example above, the variable prog is declared as an integer type variable. The next statement is the cin statement. The cin statement waits for input from the user’s keyboard that is then stored in the integer variable prog.
The input stream cin wait before proceeding for processing or storing the value. This duration is dependent on the user pressing the RETURN key on the keyboard. The input stream cin waits for the user to press the RETURN key then begins to process the command. It is also possible to request input for more than one variable in a single input stream statement. A single cin statement is as follows:
cin >> x >> y;
is the same as:
cin >> x;
cin >> y;
In both of the above cases, two values are input by the user, one value for the variable x and another value for the variable y.
// This is a sample program This is a comment Statement
#include <iostream.h> Header File Inclusion Statement
void main()
{
int sample, example;
cin >> sample;
cin >> example;
}
|
If a programmer wants to write comments in C++ program, the comments should follow after a pair of slashes denoted by //. All the characters after the // are ignored by C++ compiler and the programmer can choose to comment after the //.
In the above example, two integer variables are input with values. The programmer can produce input of any data type. It is also possible to input strings in C++ program using cin. This is performed using the same procedures. The vital point to note is cin stops when it encounters a blank space. When using a cin, it is possible to produce only one word. If a user wants to input a sentence, then the above approach would be tiresome. For this purpose, there is a function in C++ called getline.
|