CodeBlanks Logo Icon CodeBlanks

std::cout

Learn to print text and variables with std::cout.

std::cout

std::cout is the standard output stream; it prints text to the screen. The << operator sends data to the output stream. Multiple values can be chained together.

For example, std::cout << "Score: " << 95 << std::endl; prints Score: 95 and ends the line. std::endl both adds a newline and flushes the buffer.

The std:: prefix in std::cout marks the standard namespace; it is defined in the iostream header.

std::endl and \n

There are two ways to move to a new line: std::endl and "\n". Both move the cursor to the next line.

std::endl additionally flushes the buffer: it writes the output to the screen immediately. "\n" only adds a newline character and is faster.

When printing many lines, "\n" is preferred for performance; use std::endl when output must appear immediately. You can mix both in the same program.

Practice Print two lines

Add two std::cout lines inside main. The first line should print Welcome, the second Learning C++. End each line with std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Print two lines
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Print two lines
    std::cout << "Welcome" << std::endl;
    std::cout << "Learning C++" << std::endl;
    return 0;
}

Expected output

Welcome
Learning C++

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Output stream operator

Question
std::cout ____ "Hello" << std::endl;
Answer
std::cout << "Hello" << std::endl;

Explanation: The << operator sends data to the output stream.

2 What does std::endl do?

main.cpp
std::cout << "Line 1" << std::endl;
  • It only adds a blank line
  • It terminates the program
  • It adds a newline and flushes the buffer Correct answer
  • It changes the output color

Explanation: std::endl adds a newline and flushes the buffer.

3 Match the output concepts

Term Meaning
std::cout Output stream
<< Output operator
std::endl Newline and flush
std:: Standard namespace

All lessons in Beginner