Input in C++ with cin

This tutorial explains how to take input in C++ with cin.

One of the first things you’ll learn in C++ is the use of the cout, used to print text onto the console screen. It has another counterpart called cin which is used to take input from the user through the console. We’ll be discussing cin and it’s usage here in this article.

The out in cout stands for output, and the in in cin stands for input.


C++ User Input

The following code is very simple. It takes from the user an integer (x) with cin and then prints it on to the screen with cout. It’s necessary to store the input from the user somewhere, which is why we create the variable x and place it in the cin statement.

int main () {
    int x;

    cin >> x;
    cout << x;
}

Notice how the “greater than” signs are different in both cin and cout.

Some languages (like Python) will automatically convert all inputs to string datatype, however in C++ you can directly take a number as input.


Calculator Input Example

Another common usage of the cin keyword is in calculators. Below is a basic example of a C++ calculator and how cin is used to take input.

#include <iostream>
using namespace std;

int main () {
    int x, y;

    cout << "Enter number 1: ";
    cin >> x;
    cout << "Enter number 1: ";
    cin >> y;
    cout << x + y;
}

The output from the console: (3 and 5 were the numbers we entered)

Enter number 1: 3
Enter number 1: 5
8

Bonus: >> is known as the extraction operator, and << is known as the insertion operator.


This marks the end of the Input in C++ with cin tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments