Monday, September 29, 2008

Communication through console

The console is the basic interface of computers, normally it is the set composed of the keyboard and the screen. The keyboard is generally the standard input device and the screen the standard output device.

In the iostream C++ library, standard input and output operations for a program are supported by two data streams: cin for input and cout for output. Additionally, cerr and clog have also been implemented - these are two output streams specially designed to show error messages. They can be redirected to the standard output or to a log file.

Therefore cout (the standard output stream) is normally directed to the screen and cin (the standard input stream) is normally assigned to the keyboard.

By handling these two streams you will be able to interact with the user in your programs since you will be able to show messages on the screen and receive his/her input from the keyboard.

Output (cout)

The cout stream is used in conjunction with the overloaded operator << (a pair of "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the content of variable x on screen

Input (cin).

Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. This must be followed by the variable that will store the data that is going to be read. For example:

int age;
cin >> age;

Source : Cplusplus.com

No comments: