Trusted answers to developer questions

How to get user input in C++

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A good application gives a user a wonderful experience upon using it. Sometimes, accepting user input is how the application interacts with the user. Thus, a good experience can involve telling the user that they are not alone.

In C++, cin is used to collect user input.

What is cin?

cin is a predefined object in C++ and an instance of class <iostream>. It is used to accept the input from the standard input device, i.e., keyboard.

The “c” stands for character and the “in” stands or input, hence cin stands for “character input.”

Syntax


cin >> [user input]

The cin uses the extraction operator >>. The other part is the user input which could be any character from the keyboard.

Code

We will create an application that allows users to enter their names and age in the following example.

#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "What is your name?\n";
cin >> name;
cout << "Hello I'm " << name << endl;
cout << "\nWhat is your age?\n";
cin >> age;
cout << "My age is " << age;
return 0;
}

Output


What is your name?
Theodore
Hello I'm Theodore

What is your age?
19
My age is 19

Explanation

In the code above, we included the <string> library to use it.

The user is allowed to enter the required inputs. This shows that cin >> will enable us to input any value of our choice.


We used the sibling of cin >>, which is cout <<. This enables us to output values to the console.

RELATED TAGS

c++
input

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?