cout: Printing in C++

Print with cout and <<, end lines with endl, and show true/false with boolalpha.

C++ · beginner · 5 min · 8 steps · free

What you'll learn

cout_basics.cpp

#include <iostream>
using namespace std;

int main() {
    int apples = 3;
    double price = 0.5;
    bool fresh = true;
    cout << "Apples: " << apples << endl;
    cout << "Cost: " << apples * price << endl;
    cout << boolalpha << "Fresh? " << fresh << endl;
    return 0;
}

Step by step

  1. An int on the stack.
  2. price is created on the stack with the value 0.5.
  3. fresh is created on the stack with the value true.
  4. cout << sends each value to the output in turn; endl ends the line.
  5. Expressions are worked out first: 3 × 0.5 = 1.5.
  6. boolalpha prints bools as true/false instead of 1/0.
  7. The method returns 0.
  8. Three lines printed. cout works out each type itself, no format codes needed.

Common mistakes

Best practices

Key takeaways

Check yourself

cout << "a" << 1 << endl prints?

Answer: a1 and a new line. No spaces are added.

Without boolalpha, true prints as?

Answer: 1. bool is a number by default.

More in C++ Basics