All lessons
LESSON 6/53Storing Information
Reading Input
GOALLet the user type something into your program.

cin is the opposite of cout: instead of writing out, it reads what the user types into a variable. Notice the arrows >> point the other way.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << "Sum = " << a + b << endl;
return 0;
}> what you see
(input: 4 6) Sum = 10
//LINE BY LINE
Watch it run
int a, b; declares two boxes, and for now there is nothing inside them.
Reading several values
Chain >> to read several values at once. cin treats spaces and new lines as separators.
int a, b;
cin >> a >> b; // "3 4" эсвэл дараалсан хоёр мөр
cout << a + b << endl;cin >> works the same whether the numbers arrive on one line or on separate lines.
When the input does not match
If you ask for an int and a letter arrives, cin fails: the variable becomes 0 and every later read stops working.
int n;
if (cin >> n) {
cout << "Got " << n;
} else {
cout << "That was not a number";
}