C++ Programming: Objects, RAII and the STL · C++ Basics

cout: Printing in C++

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

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.