2 minute read

Introduction

The » operator, also known as the extraction operator, is a powerful tool in C++ for inputting data into variables. It is typically used in conjunction with the cin function, which is a part of the iostream library. In this article, we will discuss the usage and behavior of the » operator in C++.

Usage

The » operator is used to extract data from the input stream (typically the console) and store it in a variable. The general syntax for using the » operator is as follows:

cin >> variable;

In this example, the cin function reads input from the console, and the » operator extracts the input and stores it in the variable on the right side.

Multiple Inputs

It is also possible to extract multiple inputs at once by chaining the » operator. For example:

cin >> variable1 >> variable2 >> variable3;

This will extract input from the console and store it in each variable in the order they are listed.

Delimiters

The » operator uses whitespace as a delimiter to separate input. This means that if the input from the console is “1 2 3”, the » operator will extract the first number “1” and store it in the first variable, then extract the second number “2” and store it in the second variable, and so on.

Error Handling

If the input cannot be converted to the data type of the variable, the cin function will set a fail bit, which can be checked with the fail() function. For example:


cin >> variable;
if (cin.fail()) {
    //error handling code
}

Conclusion

The » operator is a versatile tool in C++ for inputting data into variables. It can be used in conjunction with the cin function to extract input from the console and store it in variables. It is important to remember that the » operator uses whitespace as a delimiter and to handle any input errors with the fail() function.