main, input and output

C++ · Essentials · 10 min

Every program starts in main, and console I/O is how you try out everything else in this course.

A C++ program starts in main. It returns an int to the operating system: 0 means success, anything else signals failure. main is the one function where you may leave out the return; reaching the closing brace returns 0.

Standard library names live in the namespace std, so you write std::cout, std::string and so on. You get them by including headers: <iostream> for console streams, <string> for strings.

  • std::cout << x writes to standard output. << returns the stream, so calls chain: std::cout << "a" << 1 << '\n';.
  • std::cerr is standard error, for diagnostics.
  • std::cin >> x reads one whitespace-separated value and converts it to the type of x. The expression is false if reading failed, so test it.
  • std::getline(std::cin, s) reads a whole line, spaces included.

Prefer '\n' over std::endl: endl also flushes the buffer, which is slow in loops. A classic gotcha is mixing >> and getline: after std::cin >> n the newline is still waiting in the input, so the next getline returns an empty line.

C++20 added std::format (header <format>) for Python-style formatting, std::format("{} is {}", name, age), and C++23 adds std::println in <print>, which formats and prints in one call. Streams are still everywhere in existing code, so learn both.

Avoid using namespace std; at file scope in real projects; it pulls hundreds of names into scope and causes clashes. Writing std:: is the norm.

Example

#include <iostream>
#include <string>

int main() {
    std::cout << "What's your name? ";
    std::string name;
    std::getline(std::cin, name);           // whole line, spaces included
    std::cout << "Hello, " << name << "!\n";

    int a = 0, b = 0;
    std::cout << "Two numbers: ";
    if (std::cin >> a >> b) {               // false if the input wasn't numbers
        std::cout << a << " + " << b << " = " << a + b << '\n';
    } else {
        std::cerr << "That was not a number\n";
        return 1;                           // non-zero: failure
    }
}   // falling off the end of main returns 0

Remember

  • main returns int; 0 means success
  • << writes, >> reads one token, std::getline reads a line
  • Use '\n' instead of std::endl unless you really need a flush
  • C++20 std::format and C++23 std::println are the modern formatting tools

Watch out for

  • Calling std::getline right after std::cin >> n and getting an empty string because the newline was left in the input.

Check yourself

  1. The user types `42 apples` and the program runs `std::cin >> n >> word;` with int n and std::string word. What ends up in word?
  2. Why is `'\n'` usually preferred over `std::endl`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: en.cppreference.com/w/cpp/language/main_function