Loading lessons...
I/O Streams Overview
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.cinis the standard one tied to the keyboard.ostream- an output stream.coutis the standard one tied to the screen.
Writing with <<
The insertion operator << pushes values into an output stream:
cout << "Hello " << "world!" << endl;
Each << puts one more chunk of data onto the stream, and the stream carries it to the screen.
Reading with >>
The extraction operator >> pulls values out of an input stream into variables:
int age;
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
For cin >>, whitespace splits the input into tokens. So cin >> name reads just one word - enter "John Smith" 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 >> idea, and writing uses the same <<. Change the source, and the logic barely changes.
TL;DR
- A stream is a channel that carries data in or out.
istreamis input (cin);ostreamis output (cout).<<inserts data into a stream;>>extracts data from it.cin >>stops at whitespace, so it reads one token at a time.- Streams abstract away the source and destination.