• Home
  • 2.4 Stream Insertion Operator (<<)

2.4 Stream Insertion Operator (<<)

View Categories

2.4 Stream Insertion Operator (<<)

1 min read

Table of Contents

The stream insertion operator (<<) is used to send data to an output stream. It inserts values into the stream from left to right, allowing text, variables, and expressions to be displayed on the console.

The insertion operator is most commonly used with std::cout, but it can also be used with other output streams such as file streams and string streams. Multiple values can be inserted into the same statement by chaining the operator.

Source Code #

#include <iostream>

int main()
{
    int age = 21;
    float height = 5.8f;
    char grade = 'A';

    std::cout << "Age: " << age << '\n';
    std::cout << "Height: " << height << '\n';
    std::cout << "Grade: " << grade << '\n';

    return 0;
}

Output #

Age: 21
Height: 5.8
Grade: A

Explanation #

  • The stream insertion operator (<<) inserts data into an output stream.
  • std::cout is the standard output stream object used to display information on the console.
  • The operator works from left to right, inserting each value into the output stream in sequence.
  • String literals, variables, character values, and numeric values can all be inserted using the same operator.
  • Multiple insertion operators can be chained together in a single statement to produce formatted output.
  • The insertion operator automatically converts built-in data types to their textual representation before displaying them.
  • '\n' inserts a newline character after each output statement.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *