streams - sluczak/cpp_by_example GitHub Wiki

Return to the previous lesson namespaces

Streams (basics)


Examples for this part available on git after calling the command:

git checkout -b origin streams

Idea of streams

Streams in C++ provides a simple In-Out operations handling. The most common operations are:

  • 'printing' out something on user display and
  • collecting user input from keyboard.

Streams in C++ are accesible after including the Standard Template Library (STL).

#include <iostream>

The idea of stream is that specific data flows to the specified target or from specified source.

Because is a part of standard C++ libraries, it is necessary to use the std namespace in order to access its containings.

Techniques of accessing the namespaces are described in namespaces wiki page.

Streams introduce the << and >> operators, which define the direction of stream flow.

Example below shows the usage of cin , cout and endl stream objects.

#include <iostream>

int main() {
    std::cout << "Hello, how old are you?" << std::endl;
    int age;
    std::cin >> age;
    std::cout << "Your age is " << age << std::endl;
    std::cout << "I " << "concatenate " << std::endl << "STREAMS" << "!" << std::endl;
    return 0;
}

Brief description:

cout is a stream object which stands for "standard output". Commonly, standard output is simply a user interface (console).

cin is a stream object which stands for "standard input". Commonly, standard input is user's keyboard. Program waits on cin call until application user press ENTER key.

endl is an "end of the line" character. It is mostly used to format aesthetic communicates on the console.

Please notice that...

  1. The first object in every stream line is always a stream source or target (ex. cin, cout)
  2. Streams may be concatenated by combining several objects in single line, but every object has to be followed by an appropriate stream operator (>> or <<).
  3. stream targets accepts various object types, so you may send to the cout int, string, char and plenty of different types of objects and even concatenate them in single stream.
  4. You cannot change the stream direction in single instruction, so this call won't compile: c++ std::cout << "I try to " >> "change stream direction";
  5. there are additional iostream types. Please refer C++ reference specification

Proceed to the next leson: flow control

⚠️ **GitHub.com Fallback** ⚠️