Camp 1 · Step 3 of 12
cin, cout, and streams
Master input and output together — read values, print results, and build a tiny interactive program.
Output and input are two directions of one idea: streams. Let's use both and make a program that responds.
Output: chaining cout
One cout can chain many pieces with << — text, numbers, computed
expressions, all flowing out left to right. No format placeholders like
C's %d; the stream figures out each type itself. That's a real C++
comfort over C.
Input: cin into variables
std::cin >> reads typed input and stores it. The arrows reverse — data
flows from the input into your variable:
#include <iostream>
int main() {
std::string name;
int age;
std::cout << "Name: ";
std::cin >> name; // read a word into name
std::cout << "Age: ";
std::cin >> age; // read a number into age
std::cout << "Hello " << name << ", next year you're "
<< age + 1 << std::endl;
return 0;
}cin >> is smart about types: reading into an int parses a number, into
a std::string grabs a word. (Our sandbox can't accept live typing, so
input examples are shown as code — run them on your own machine to try.)
The symmetry
| Operator | Stream | Direction |
|---|---|---|
<< | cout | data flows out to the screen |
>> | cin | data flows in from the keyboard |
Remember it by the arrows: they always point the way the data moves.
Which reads a number typed by the user into a variable n?
An advantage of C++ streams over C's printf is…