Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Printing with std::println
    4. Format specs: width, alignment and fill
    5. Format specs: precision and number bases
    6. Choosing the argument: {0}, {1}
    7. Building a string with std::format
    8. The format string is checked when you compile
    9. Streams: std::cout and std::cin
    10. Reading numbers with >>
    11. Checking that the read worked
    12. Reading whole lines with std::getline
    13. Error messages: std::cerr
    14. Which one should I use?
    15. Under the hood
    16. Common pitfalls
    17. getline after >> reads an empty line
    18. Using the result of a failed read
    19. Try it yourself

    Module 1 · Basics

    1.6Printing and reading: std::print, std::format and streams

    Print text and numbers with std::println, line them up with format specs, build strings with std::format, and read numbers and lines with std::cin, checking that the input was what you expected.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Printing with std::println
    4. Format specs: width, alignment and fill
    5. Format specs: precision and number bases
    6. Choosing the argument: {0}, {1}
    7. Building a string with std::format
    8. The format string is checked when you compile
    9. Streams: std::cout and std::cin
    10. Reading numbers with >>
    11. Checking that the read worked
    12. Reading whole lines with std::getline
    13. Error messages: std::cerr
    14. Which one should I use?
    15. Under the hood
    16. Common pitfalls
    17. getline after >> reads an empty line
    18. Using the result of a failed read
    19. Try it yourself

    Key terms

    std::print / std::println
    Print text with values filled in. println adds a newline at the end; print doesn't. From <print>.
    format string
    The text you pass first to std::println or std::format, with {} placeholders where the values go.
    placeholder ({})
    A pair of braces in a format string. Each one is replaced by the next argument.
    format spec
    Instructions after a : inside a placeholder, like {:>8} or {:.2f}, that say how to print the value.
    width
    The least number of characters a value takes up. Shorter values are padded.
    alignment
    Where a value sits inside its width: < left, > right, ^ centered.
    fill
    The character used for padding, written before the alignment, like * in {:*^20}.
    precision
    For a floating-point number, how many digits to show after the decimal point: {:.2f}.
    std::format
    Works like std::println, but returns the text as a std::string instead of printing it. From <format>.
    stream
    An object you write text to or read text from in order, like std::cout or std::cin. From <iostream>.
    standard output (stdout)
    Where a program's normal output goes: usually the terminal. std::println and std::cout write here.
    standard input (stdin)
    Where a program reads its input: what you type, or a file you send to it. std::cin reads from here.
    standard error (stderr)
    A second output, kept apart from stdout, for error messages. std::cerr writes here.
    << and >> on streams
    std::cout << x writes x to the stream; std::cin >> x reads a value from the stream into x.
    whitespace
    Spaces, tabs and newlines. >> skips it before a value and stops reading at it.
    flush
    To send text that is waiting in a buffer out to the terminal or file right away.

    A program is only useful if it can show you its results and take your input. Printing a number is easy; printing a table whose columns line up, a score with two decimals, or a byte in binary takes a few more words. Reading input has its own problem: people type things you didn’t expect. This lesson covers both.

    In 30 seconds

    • std::println("{} reads", n); prints text with values filled into the {} placeholders.
    • Format specs inside the braces control the look: {:>8} (width and alignment), {:.2f} (decimals), {:x} (hex), {:08b} (binary).
    • std::format builds the same text as a std::string instead of printing it. A placeholder with no argument, or a spec that doesn’t fit its argument’s type, doesn’t compile.
    • std::cin >> n reads a value and std::getline reads a whole line. Always check that the read worked.

    Printing with std::println

    Include <print> and call std::println with a format string and the values to fill in. Each {} placeholder is replaced by the next argument, whatever its type. std::println ends the line for you; std::print doesn’t, so the next output continues on the same line.

    #include <print>
    
    int reads = 1200;
    double quality = 37.5;
    std::println("Reads: {}, mean quality: {}", reads, quality);
    std::print("no newline, ");
    std::print("so this continues\n");
    std::println("{{}} prints braces");

    Output

    Reads: 1200, mean quality: 37.5
    no newline, so this continues
    {} prints braces

    \n inside a string is the newline character. To print a brace itself, double it: {{ prints { and }} prints }.

    Format specs: width, alignment and fill

    Put a : inside the braces and you can add a format spec. A number after the colon is the width: the value takes up at least that many characters. <, > and ^ set the alignment: left, right or centered. Without one, numbers line up on the right and text on the left. A character before the alignment is the fill, used instead of spaces.

    #include <print>
    
    std::println("[{:>8}]", "right");
    std::println("[{:<8}]", "left");
    std::println("[{:^8}]", "mid");
    std::println("[{:8}]", 42);
    std::println("[{:*^20}]", " DNA ");

    Output

    [   right]
    [left    ]
    [  mid   ]
    [      42]
    [******* DNA ********]

    Widths are how you print a table whose columns line up:

    #include <print>
    
    std::println("{:<6}{:>6}", "base", "count");
    std::println("{:<6}{:>6}", "A", 312);
    std::println("{:<6}{:>6}", "G", 1045);

    Output

    base   count
    A        312
    G       1045

    Format specs: precision and number bases

    For floating-point numbers, .2f means “fixed-point, 2 digits after the point”. The value is rounded, not cut off. Width and precision combine: {:8.3f} is 8 characters wide with 3 decimals.

    For integers, x prints in hexadecimal (base 16), X in upper-case hexadecimal and b in binary. # adds the prefix (0x, 0b). A 0 before the width pads with zeros instead of spaces, so {:08b} shows all 8 bits of a byte.

    #include <print>
    
    double gc = 0.41666;
    std::println("{:.2f} {:.1f}%", gc, gc * 100);
    std::println("[{:8.3f}]", gc);
    int pixel = 200;
    std::println("{:x} {:#x} {:X}", pixel, pixel, pixel);
    std::println("{:b} {:08b} {:#b}", 5, 5, 5);

    Output

    0.42 41.7%
    [   0.417]
    c8 0xc8 C8
    101 00000101 0b101

    Choosing the argument: {0}, {1}

    A number before the colon picks an argument by position, counting from 0. You can use one argument more than once, or in a different order:

    #include <print>
    
    std::println("{0} {1} {0}", "ping", "pong");
    std::println("{1} comes after {0}", "A", "B");
    std::println("{0:>6} = {0:#x}", 255);

    Output

    ping pong ping
    B comes after A
       255 = 0xff

    Use either numbered or plain {} placeholders in one format string, not both.

    Building a string with std::format

    std::format, from <format>, takes the same format string and arguments, but returns the text as a std::string instead of printing it. Use it when you need the text itself: a file name, a label, a message to pass on.

    #include <format>
    #include <print>
    #include <string>
    
    std::string label = std::format("sample_{:03}", 7);
    std::println("{} has {} characters", label, label.size());

    Output

    sample_007 has 10 characters

    The format string is checked when you compile

    The compiler reads the format string and checks it against the arguments. A placeholder with no argument to fill it is a compile error, not a surprise at run time:

    #include <print>
    
    int reads = 1200;
    std::println("{} reads, mean quality {}", reads);

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:14: error: call to consteval function ‘std::basic_format_string<char, int&>("{} reads, mean quality {}")’ is not a constant expression
        4 | std::println("{} reads, mean quality {}", reads);
          |              ^~~~~~~~~~~~~~~~~~~~~~~~~~~
    compilation terminated due to -fmax-errors=1.

    GCC’s first error points at the format string and says it “is not a constant expression”: the check, which runs while compiling, failed. On your own machine more lines follow, from inside the library’s code; among them, the name invalid_arg_id_in_format_string says a placeholder asks for an argument that isn’t there. The same check catches a spec that doesn’t fit the type, like {:.2f} for a string. The fix is to make the placeholders and the arguments match: here, pass the quality too.

    Modern C++std::print is new in C++23

    std::format arrived in C++20 and std::print and std::println in C++23. Older code prints with std::cout (next section) or printf from <cstdio>, which doesn’t check its arguments at all.

    Streams: std::cout and std::cin

    <iostream> gives you streams: std::cout writes to standard output, and std::cin reads from standard input. << sends a value into std::cout, and you can chain as many as you like:

    #include <iostream>
    
    int count = 3;
    std::cout << "count: " << count << '\n';
    std::cout << "done" << std::endl;

    Output

    count: 3
    done

    std::endl writes a newline and then flushes the stream: it makes sure the text has really been sent out, which takes extra time. '\n' writes only the newline, and is usually what you want.

    Reading numbers with >>

    std::cin >> x reads a value into x. It skips any whitespace (spaces, tabs, newlines) first, then reads characters as long as they fit the type of x. This program is run with the input 3 4:

    #include <iostream>
    #include <print>
    
    int a = 0;
    int b = 0;
    std::cin >> a >> b;
    std::println("{} + {} = {}", a, b, a + b);

    Output

    3 + 4 = 7

    Checking that the read worked

    If the input isn’t a number, >> can’t read an int. It sets the variable to 0 and puts std::cin into a failed state. Every later read does nothing until you deal with it. A stream can be used as a condition: it’s true if the last read worked. So check the read itself. This program gets abc as its input:

    #include <iostream>
    #include <print>
    
    int n = 0;
    if (std::cin >> n) {
        std::println("you typed {}", n);
    } else {
        std::println("That isn't a whole number. Type one like 42.");
    }

    Output

    That isn't a whole number. Type one like 42.

    The same test makes a loop that reads values until the input runs out (or isn’t a number):

    #include <iostream>
    #include <print>
    
    int total = 0;
    int value = 0;
    while (std::cin >> value) {
        total += value;
    }
    std::println("total: {}", total);

    Output

    total: 49

    !std::cin is the opposite test: it’s true after a read has failed.

    Reading whole lines with std::getline

    >> reads into a std::string one word at a time: it stops at the first whitespace. std::getline(std::cin, line), from <string>, reads everything up to the end of the line, spaces included. Like >>, it can be used as a condition, so it can drive a loop over every line of the input:

    #include <iostream>
    #include <print>
    #include <string>
    
    std::string word;
    std::cin >> word;
    std::println("word: [{}]", word);
    
    std::string line;
    while (std::getline(std::cin, line)) {
        std::println("line: [{}]", line);
    }

    Output

    word: [read_1]
    line: [ GATTACA]
    line: [read_2 CCGG]

    >> read read_1 and stopped at the space, so the first std::getline got the rest of that line, space included.

    Error messages: std::cerr

    std::cerr writes to standard error, a second output kept apart from standard output. Use it for error messages and warnings, so they don’t get mixed into the results when someone saves the output to a file. std::println(stderr, …) does the same with a format string; stderr comes from <cstdio>.

    #include <cstdio>
    #include <iostream>
    #include <print>
    
    int count = 0;
    std::cin >> count;
    if (count < 0) {
        std::cerr << "count can't be negative; using 0\n";
        std::println(stderr, "you typed {}", count);
        count = 0;
    }
    std::println("count: {}", count);

    Output

    count: 0

    The output block on this site shows only standard output, so the two error lines don’t appear in it. In a terminal you’d see all three lines.

    Which one should I use?

    WhatWhenWhyHow
    std::println / std::printPrinting anything in new code.Short, the format is checked when you compile, and it’s fast.std::println("{:>8.2f}", x);
    std::formatYou need the text as a string, not printed.Same format specs as println.auto name = std::format("run_{:03}", i);
    std::coutCode that already uses streams, or a library that writes to a stream.It’s what older code and many libraries use.std::cout << x << '\n';
    std::cin >>Reading numbers or single words.It skips whitespace and converts the text to your type.if (std::cin >> n) { … }
    std::getlineReading a whole line, spaces included.It keeps the line exactly as typed.while (std::getline(std::cin, line)) { … }
    std::cerr or std::println(stderr, …)Error messages and warnings.They stay out of the program’s normal output.std::println(stderr, "bad input: {}", s);

    Rule of thumb: print with std::println, read with std::cin or std::getline, and put every read inside an if or a while.

    Under the hood

    Output isn’t sent to the terminal one character at a time. The program collects it in a buffer, a block of memory, and sends it in larger pieces, which is much faster. When standard output goes to a terminal, the buffer is usually sent at each newline; when it goes to a file, only when it fills up or the program ends. Standard error isn’t buffered, so an error message appears at once, even if the program crashes right after.

    That’s why std::endl costs more than '\n': it forces the buffer out every time. In a loop that prints many lines, that adds up.

    The compile-time check works because the format string is a constant the compiler can read. std::println doesn’t take a plain string as its first argument; it takes a special format-string type that parses the string while the program is being compiled and compares each placeholder with the argument types. A format string that’s only known when the program runs, such as one read from a file, needs std::vformat, which checks it at run time instead.

    Common pitfalls

    getline after >> reads an empty line

    std::cin >> age reads the number and stops before the newline that follows it. The next std::getline sees that newline straight away and returns an empty line:

    #include <iostream>
    #include <print>
    #include <string>
    
    int age = 0;
    std::cin >> age;
    std::string name;
    std::getline(std::cin, name);
    std::println("age {}, name [{}]", age, name);

    Output

    age 42, name []

    Skip the leftover whitespace first with std::ws, which reads and throws away spaces and newlines:

    #include <iostream>
    #include <print>
    #include <string>
    
    int age = 0;
    std::cin >> age;
    std::string name;
    std::getline(std::cin >> std::ws, name);
    std::println("age {}, name [{}]", age, name);

    Output

    age 42, name [Ada Lovelace]

    Using the result of a failed read

    If you don’t check, a failed read looks like a real 0, and every read after it fails too. Here the first read fails on ten, so a becomes 0, and b is never read at all:

    #include <iostream>
    #include <print>
    
    int a = -1;
    int b = -1;
    std::cin >> a >> b;
    std::println("{} {}", a, b);

    Output

    0 -1

    Put the read in an if, as in Checking that the read worked, and tell the user what to type instead.

    Key ideaInput is never guaranteed

    Whatever you ask for, people can type something else, and input can end at any moment. Treat every read as something that might fail: read inside an if or a while, and say what you expected when it doesn’t work.

    Try it yourself

    Try it yourself

    The program reads names and scores until the input ends. Make it print them as a table, names left-aligned in 8 characters and scores right-aligned in 5, then an average row with one decimal. It’s run with this input: Ada 91, Grace 78, Linus 85, one per line.

    #include <iostream>
    #include <print>
    #include <string>
    
    int main() {
        std::string name;
        int score = 0;
        while (std::cin >> name >> score) {
            std::println("{} {}", name, score);
        }
    }

    Expected output

    Ada        91
    Grace      78
    Linus      85
    average  84.7
    Show a hint

    Read inside the condition: while (std::cin >> name >> score). Use {:<8} for the name and {:>5} for the score, and {:>5.1f} for the average, which is a double.

    Show a solution
    #include <iostream>
    #include <print>
    #include <string>
    
    int main() {
        std::string name;
        int score = 0;
        int total = 0;
        int count = 0;
        while (std::cin >> name >> score) {
            std::println("{:<8}{:>5}", name, score);
            total += score;
            ++count;
        }
        if (count > 0) {
            double average = static_cast<double>(total) / count;
            std::println("{:<8}{:>5.1f}", "average", average);
        }
    }

    The while condition reads a name and a score and stops when the input runs out. {:<8} pads each name to 8 characters on the right, and {:>5} lines the numbers up on the right. The average is converted to double before dividing so it keeps its fraction, and .1f rounds it to one decimal.

    Saved in this browser only.