Basic Input /Output in C++

With the help of examples, we will learn how to use the cin object to take user input and the cout object to display output to the user in this tutorial.

The stream concept is used in C++ I/O operations. The sequence of bytes or flow of data is referred to as a stream. It will speed up the performance.

When bytes flow from main memory to a device such as a printer, display screen, or network connection, this is referred to as an output operation.

Input operations occur when bytes flow from a device such as a printer, display screen, or network connection to the main memory.

Basic Input /Output in C++

Basic Input /Output in C++

Let us look at some of the most common header files used in C++ programming:

Header file The functions as well as a description
<iostream> It is mainly used in order to define the cout, cin, and cerr objects, which will always correspond to the standard output stream, standard input stream, as well as standard error stream, respectively.
<iomanip> It's used to declare services like set precision and setw that are useful for performing formatted I/O.
<fstream> It is used to declare user-controlled file processing services.

Output in C++

cout in C++ sends formatted output to standard output devices like the screen. For output display, the cout object and the << operator are used.

An example of obtaining  String Output

#include <iostream>
using namespace std;

int main() {
    // prints the string which should be enclosed in double quotes
    cout << "This is learn eTutorials";
    return 0;
}

Output:


This is learn eTutorials

Working of this Program

  • We begin by including the iostream header file, which enables us to display output.
  • Within the std namespace is where the cout object is defined. We used the using namespace std; statement to use the std namespace.
  • The main() function is the first line of code in every C++ program. The main() function is where the code execution begins.
  • cout is an object that prints the string " " enclosed in quotation marks. return 0; is the "exit status" of the main() function and is immediately followed by the operator. The program concludes with this statement, but it is not considered necessary.
Important Note :
  • If the using namespace std; statement is not included, we must use std::cout instead of cout
  • This is the preferred method because using the std namespace may cause some issues. 
  • However, in our tutorials, we used the std namespace to make the code more readable.

A sample program that shows how to use std::cout instead of cout.


#include <iostream>

int main() {
    //always  prints the string that should be enclosed in double quotes
    std::cout << "This is an amazing method";
    return 0;
}

Output:


This is an amazing method

An example of how to use the same cout object to print the numbers and character variables, but without quotation marks.


#include <iostream>
using namespace std;

int main() {
    int num1 = 40;
    double num2 = 125.703;
    char ch = 'A';

    cout << num1 << endl;    // print integer
    cout << num2 << endl;    // print double
    cout << "character: " << ch << endl;    // print char
    return 0;
}

Output:


40
125.703
character: A

A new line is inserted using the endl manipulator. As a result, each output is displayed on a new line.

If we want to print multiple variables, strings, and so on in a single statement, we can use the operator multiple times.


cout << "character: " << ch << endl;
 

Input in C++

cin accepts formatted input from standard input devices such as the keyboard in C++. We take input using the cin object and the >> operator.

An example for integer input/ output


#include <iostream>
using namespace std;

int main() {
    int num;
    cout << " please enter an integer and wait: ";
    cin >> num;   // Taking input
    cout << "The number is: " << num;
    return 0;
}

Output:


please enter an integer and wait: 3
The number is: 3

We used cin >> num; in the program in order to collect user input. The variable num stores the input. To accept input, we use the >> operator with cin.

If the, using namespace std; statement is not included, we must use std::cin instead of cin.

An example of a C++ program taking multiple inputs


#include <iostream>
using namespace std;

int main() {
    char a;
    int num;

    cout << " please enter a character and an integer with a smile: ";
    cin >> a >> num;

    cout << "Character: " << a << endl;
    cout << "Number: " << num;

    return 0;
}

Output:


please enter a character and an integer with a smile: T 100
Character: T
Number: 100

The Error Stream Standard (cerr)

Cerr is a predefined object that is an instance of the iostream class. The standard error device, which also serves as a display screen, is said to be attached to the cerr object. However, the object cerr is not buffered, so each stream insertion into cerr causes its output to be displayed immediately.

As shown in the following example, the cerr is also used in conjunction with the stream insertion operator.


#include <iostream>
 
using namespace std;
 
int main() {
   char str[] = "not able to read....";
 
   cerr << "Error message : " << str << endl;
}

Output:


Error message : not able to read....

The Standard Log Stream (clog)

An instance of the ostream class is the predefined object clog. The standard error device, which is also a display screen, is said to be attached to the clog object, but the object clog is buffered. This means that each insertion into clog may cause its output to be held in a buffer until it is filled or flushed.

As shown in the following example, the clog is also used in conjunction with the stream insertion operator.


#include <iostream>
 
using namespace std;
 
int main() {
   char str[] = " not able to read....";
 
   clog << "Error message detected : " << str << endl;
}

Output:


Error message detected :  not able to read....

You wouldn't notice any difference in cout, cerr, or clog with these small examples, but the difference becomes more evident when writing and running large programs. So, when displaying error messages, use the cerr stream, and when displaying other log messages, use clog.

Input/Output from an external file in C++ mainly for Competitive Programming

Most of the time in Competitive Programming, we must manually enter input to check our code. However, if we have questions like graphs, strings, or bulky input data entry, it will definitely time out or the chances of typing incorrect data will increase.

We can easily solve the problem by simply saving the test cases to the specified file in the desired location. These are useful in competitions such as the Facebook Hackercup and the Google Codejam. These competitions do not provide an online judging environment; instead, you must upload input and output files.

We primarily use these two types of file access modes for Input/Output, namely,

  • r: "r" stands for read, as it opens the file for input, but the file must exist at the specified location.
  • w:  "w" stands for "write," because it creates an empty file for output operations. If a file with the same name already exists, the contents of that file are discarded, and the file is treated as a new empty file.

For standard input and output, we can use freopen in C/C++. This function's syntax is as follows:

Syntax


FILE * freopen(const char * filename, const char * mode, FILE * stream );

filename: This is the name of the file we want to open.

mode: As previously stated( use these two types of file access modes for Input/Output, namely, r and w)

stream: pointer to a FILE object that identifies the stream that needs to be reopened.