Lesson 196 +10 XP

I/O Streams Overview

A stream is a channel of flowing data. In C++, input streams carry data into your program, and output streams carry data out of it. The same idea powers the console, files, and even strings.

The two sides

  • istream - an input stream. cin is the standard one tied to the keyboard.
  • ostream - an output stream. cout is the standard one tied to the screen.

Writing with <<

The insertion operator << pushes values into an output stream:

Code

cpp
cout << "Hello " << "world!" << endl;

Each &lt;&lt; puts one more chunk of data onto the stream, and the stream carries it to the screen.

Reading with &gt;&gt;

The extraction operator &gt;&gt; pulls values out of an input stream into variables:

Code

cpp
int age;
string name;

cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;

For cin &gt;&gt;, whitespace splits the input into tokens. So cin &gt;&gt; name reads just one word - enter &quot;John Smith&quot; and only John lands in name.

Why streams unify everything

The beauty of streams is abstraction: reading from the keyboard, a file, or a string uses the same &gt;&gt; idea, and writing uses the same &lt;&lt;. Change the source, and the logic barely changes.

TL;DR

  • A stream is a channel that carries data in or out.
  • istream is input (cin); ostream is output (cout).
  • &lt;&lt; inserts data into a stream; &gt;&gt; extracts data from it.
  • cin &gt;&gt; stops at whitespace, so it reads one token at a time.
  • Streams abstract away the source and destination.