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.
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.”
cin >> [user input]
The cin
uses the extraction operator >>
. The other part is the user input which could be any character from the keyboard.
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;}
What is your name?
Theodore
Hello I'm Theodore
What is your age?
19
My age is 19
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 iscout <<
. This enables us to output values to the console.