C++ Output (cout)

cout is the object C++ uses to print text and values to the screen. It lives in the <iostream> header, along with the << operator that sends data to it.

Syntax

To output something, write cout, followed by the insertion operator <<, followed by whatever you want to print:

cout << "Hello, World!";

This prints the text between the quotes exactly as written. cout stands for “character output”, and it is part of the std namespace, which is why programs either write std::cout or add using namespace std; near the top.

Example

#include <iostream>
using namespace std;

int main(void) {
    cout << "Hello, World!";
    return 0;
}
Output:
Hello, World!

How it works

The << operator is called the insertion operator because it inserts whatever follows it into the output stream. You can read the line cout << "Hello, World!"; as “send the text ‘Hello, World!’ to cout”.

Chaining multiple values

You can use << more than once in the same statement to print several things in a row, including text, numbers, and variables:

cout << "Age: " << 25 << endl;

This prints the string "Age: " immediately followed by the number 25, with no extra spaces added automatically. If you want a space between them, you must include it yourself, either inside the quotes or as its own << " " <<.

Printing new lines

By default, cout does not move to a new line after printing. To start a new line, use either endl or the newline character \n inside a string:

  • endl — inserts a new line and flushes the output buffer
  • \n — inserts a new line without flushing, and can be placed inside any string

Example

#include <iostream>
using namespace std;

int main(void) {
    cout << "C++ is fun!" << endl;
    cout << "Learning is easy.\n";
    cout << "Age: " << 25 << endl;
    return 0;
}
Output:
C++ is fun!
Learning is easy.
Age: 25

In everyday code, \n is often preferred for performance since it skips the extra flush that endl performs, but both work correctly for beginner programs.

Now that you can print output, the next lesson covers how to read input from the user with cin.