C++

C++ Input and Output

C++ Input and Output

In this section, we will see look into the Input/output capabilities in C++. The C++ standard libraries provide  rich I/O capabilities (Input output). This section will touch upon very basic I/O operations that are commonly used in C++ programming.

C++ input output is associated with streams. Streams are sequences of bytes that flow in some direction. For input, bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory and for output, bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc. Some common headers used for i/o are given below

  1. <iostream> it provides cout, cin and cerr objects corresponding to standard output stream, standard input stream and standard error stream, respectively.
  2. <iomanip>   it provides methods to format I/O, such as setprecision and setw.
  3. <fstream>   it provides methods to manage file processing.

Let us discuss standard i/o objects such as cout, cin, cerr and clog. The object cout is an instance of ostream class defined in iostream. The cout object is represent standard output device i.e. console. The cout is used in conjunction with the stream insertion operator (<<) to display any object on to screen. For e.g. consider the code snippet below. It will output "Welcome to C++" on screen" when executed.

#include <iostream>
#include <string>

int main()
{
   string str = "Welcome to C++";
 
   cout << "Str is " << str << endl;
}

cin in an object of stream class. The cin object represents the standard input device i.e. the keyboard. The cin is used in conjunction with the stream extraction operator (>>) to take any input from user via keyboard. For e.g

int x;
cin>>x; //this line will take an integer as user input and store it in x

cerr is an instance of ostream class. The cerr object is connected to standard error device which in most cases is console. The object cerr is un-buffered and each stream insertion to cerr flushes its output

immediately instead of storing it in a buffer. For e.g. the following code will display the error string when this program is executed.

#include <iostream>
#include <string>

int main()
{
   string errorStr = "Generic error occured";
 
   cout << "Gener error string is " << errorStr << endl;
}

clog is an instance of ostream class. The clog object is connected to the standard error device i.e. the console. Please note that clog is buffered internally with each insertion to clog causes its output to be kept in a buffer until the buffer is filled or until the buffer is flushed.