Asking the user
cout sends things to the screen. Its partner cin (say: “see in”) reads things from the keyboard. Notice the arrows point the other way: >>.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "How old are you? ";
cin >> age;
cout << "In 10 years you will be " << age + 10 << "\n";
return 0;
}Input (what the user types)
16
Output
How old are you? In 10 years you will be 26
Think of it like this:
cin >> ageis like pouring what the user typed into theagebox. The arrows show the direction the data flows: fromcininto the variable.
In the examples in this course, the box called Input shows what the user typed. In a real terminal you would see it next to the question.
Reading several values
You can chain >> just like <<. The values can be on one line, separated by spaces, or on separate lines:
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Their sum is " << a + b << "\n";
return 0;
}Input (what the user types)
7 35
Output
Enter two numbers: Their sum is 42
Tip:
int a, b;creates two int variables in one line.
Reading a word
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "What is your name? ";
cin >> name;
cout << "Nice to meet you, " << name << "!\n";
return 0;
}Input (what the user types)
Arjun
Output
What is your name? Nice to meet you, Arjun!
Common mistake:
cin >>stops at the first space. If the user typesArjun Mehta,nameonly getsArjun. The next lesson shows how to read a whole line.