C++ Tutorial · C++ Basics · Lesson 3 of 21

C++ Syntax and Output

Statements, namespaces, comments, cout and std::format.

Syntax

  • Statements end with ;, blocks use { }, comments are // and /* */.
  • Standard library names live in the std namespace: std::cout, std::string. (Avoid using namespace std; in headers.)

Output

std::cout chains values with <<. C++20's std::format works like Python's f-strings:

Example 1
#include <format>
#include <iostream>

int main() {
    int qty = 2;
    double price = 3.5;
    std::cout << "Qty: " << qty << ", price: " << price << '\n';
    std::cout << std::format("{} x {:.2f} = {:.2f}\n", qty, price, qty * price);
    std::cout << std::format("[{:>5}] [{:<5}] [{:^7}]\n", 42, 42, "mid");
    std::cout << std::boolalpha << (qty > 1) << '\n';
}

Output

Qty: 2, price: 3.5
2 x 3.50 = 7.00
[   42] [42   ] [  mid  ]
true

Run this on your computer — see “Get Started” for setup.

Test yourself

Which header provides std::format?

  1. <string>
  2. <format>
  3. <iostream>
  4. <print>
Show answer

Answer: <format>