skip to content

Text and I/O

std::string, string_view, std::format and iostreams are how C++ handles text, each with a trap. Interviewers ask about small-string optimization, dangling views and stream state.

on this pageshow

explore

questions

22

In C++20, what does std::format return, and why is it safer than printf for building a game server's status line?

level: juniorimportance: must knowfreq 62%

answer

  1. returns a string, not a count
  2. argument types travel with the call
  3. format string checked when compiling
  4. printf trusts the conversion letters

basics

~20 s

std::format returns a std::string built from {} replacement fields. It knows every argument's type, and a literal format string is checked against those types at compile time, while printf trusts its conversion letters and misbehaves at run time on a mismatch.

solid answer

~40 s

`std::format` (C++20, header `<format>`) takes a format string such as `"{} has {} players"` plus arguments and returns a `std::string`. Each `{}` is a replacement field; the argument's type comes from the call itself, so a `std::string`, an `int` or a `double` each print correctly with no `%s`/`%d`/`%f` letters to keep in sync. The format string is a `std::format_string<Args...>` whose constructor is `consteval`, so a field that does not fit its argument (`{:d}` for a string, a missing argument) stops compilation. `printf` instead reads its variadic arguments by trusting the conversion letters: a mismatch compiles, at most with a `-Wformat` warning, and is undefined behaviour at run time. It also cannot take a `std::string` without `c_str()`.

code

cpp · 17 lines
cpp
#include <cstdio>
#include <format>
#include <iostream>
#include <string>

int main() {
    std::string server = "eu-west-3";
    int players = 118;

    std::string line = std::format("{} has {} players", server, players);
    std::cout << line << '\n';
    std::cout << std::format("{1} <- {0}", "first", "second") << '\n';
    std::cout << std::format("{{literal braces}} {}", true) << '\n';

    // printf: the letters must match and std::string needs c_str()
    std::printf("%s has %d players\n", server.c_str(), players);
}

go deeper

for a junior

Recall that std::format returns a std::string, uses {} fields, and that a mismatched field is a compile error, not a runtime surprise.

for a middle

Explain the mechanism: a variadic template keeps the argument types, and the consteval constructor of std::format_string parses the literal against them.

for a senior

Show where checking stops: runtime format strings through std::vformat, negative dynamic widths, throwing user formatters, and allocation, plus format_to for hot paths.

for a principal

Weigh the C++20 library requirement and the string allocation against printf's lack of safety when choosing an output convention for a team.

## What std::format does `std::format` arrived in **C++20** in the header `<format>`. It takes a **format string** and a list of arguments and returns a brand-new `std::string` (or `std::wstring` for a wide format string): ```cpp std::string line = std::format("{} scored {} points", player, score); ``` Each pair of braces is a **replacement field**. Text outside the braces is copied as is; each field is replaced by the next argument, formatted according to its type. Nothing is printed: you decide where the string goes, whether that is `std::cout`, a file, a socket or a log buffer. ## Why printf is not type-safe `printf` is a C variadic function. It receives its arguments without their types, and the only description of what was passed is the format string you wrote: - `%d` tells it to read an `int`, `%s` a `const char*`, `%f` a `double`. If the argument is something else, the behaviour is **undefined**: garbage output, a crash, or a read of the wrong register. - It has no conversion for `std::string`. You must remember to pass `name.c_str()`. - Swapping two arguments still compiles. Compilers such as clang and GCC can warn about it with `-Wformat` when the format string is a literal, but it is only a warning, and they cannot check a format string held in a variable. A status line such as `printf("%d players on %s", server.c_str(), players)` compiles, and clang only prints a warning. Its behaviour is undefined: `printf` will try to read a pointer where it expects an `int` and an `int` where it expects a pointer, and no output it produces can be relied on. ## How std::format knows the types `std::format` is a variadic **template**, so the compiler knows the exact type of every argument. The first parameter is not a plain string but a `std::format_string<Args...>`. Its constructor is `consteval`: it runs at compile time, parses the literal, and checks every replacement field against the matching argument type. If a field is wrong, the call is not a constant expression and the program does not compile: ```cpp std::format("{:d} points", player); // player is a std::string: compile error ``` That check was added in 2021 as a fix applied to C++20. The very first C++20 wording threw `std::format_error` at run time instead, and that still happens today when you deliberately pass a runtime format string through `std::vformat`. ## Replacement field basics - `{}` takes the next argument (**automatic indexing**). - `{0}`, `{1}` choose an argument by position (**manual indexing**), so the same value can appear twice or out of order. - Mixing `{}` and `{1}` in one string is not a valid format string. - `{{` and `}}` print literal braces. - A colon starts a format specification: `{:>8.2f}` sets alignment, width, precision and type. - `bool` prints as `true`/`false`, `char` prints as a character, and a `double` with no specification prints the shortest text that reads back as the same value. ## printf, iostreams and std::format side by side | Concern | `printf` | `std::cout <<` | `std::format` | |---|---|---|---| | Type safety | none; letters must match | yes, by overloading | yes, checked at compile time | | `std::string` argument | needs `c_str()` | yes | yes | | Layout in one place | yes, one format string | no, scattered manipulators | yes, one format string | | Result | writes to a C stream | writes to a stream | returns a `std::string` | | User types | not extensible | `operator<<` | `std::formatter` specialization | | Locale | the global C locale | the stream's locale | locale-independent unless `L` is used | ## What to know about the cost and the alternatives 1. `std::format` allocates the `std::string` it returns. When you already have a buffer, `std::format_to(std::back_inserter(buf), ...)` appends to it, and `std::formatted_size` tells you the length first. 2. It needs a C++20 standard library that ships `<format>`: libstdc++ from GCC 13.1, for example. Many codebases still on C++17 cannot use it. 3. **C++23** adds `std::print` and `std::println`, which format and write in one call. For C++20, `std::cout << std::format(...)` is the usual idiom. For a junior interview, the core answer is short. It returns a string, it uses `{}` instead of conversion letters, and the compiler, not the run time, catches a field that does not match its argument.

  • If std::format checks the format string at compile time, can it still throw?
    Yes. `std::format_error` is thrown when a format string reaches the library unchecked, through `std::vformat` with a runtime string, or when a dynamic width argument is negative. A user-defined `std::formatter` may throw from its own `format`. Allocation failure reports `std::bad_alloc`. The compile-time check covers the literal's syntax and its fit to the argument types, not every runtime value.
  • How do you avoid allocating a new std::string on every call?
    Use `std::format_to` with an output iterator into a buffer you reuse, such as `std::back_inserter(buf)` on a `std::string` you `clear()` each time, or `std::format_to_n` into a fixed `char` array. `std::formatted_size` returns the length the output would have, so you can size a buffer first.

  • std::format prints to standard output like printf does
  • Uses %d and %s conversion letters inside the format string
  • A printf type mismatch is caught by the compiler as an error
  • std::format is available in C++17 under std::experimental
  • A wrong replacement field always throws std::format_error at run time

Assumes C++20 for std::format; the compile-time format string check was a 2021 fix applied to C++20, and std::print needs C++23.

open as a page

In C++, what is the difference between writing std::endl and '\n' to an output stream, and when does it matter?

level: juniorimportance: must knowfreq 72%

basics

~20 s

std::endl writes a newline and then flushes the stream; '\n' only writes the newline and leaves it in the buffer. In a loop that writes many lines, flushing every line forces a write each time and can make output many times slower.

open as a page

In C++, what does a std::string own that a const char* does not, and what does copying each one cost?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A std::string owns a contiguous, null-terminated buffer that it allocates, copies and frees itself; a const char* is only an address. Copying a string duplicates every character into a new buffer; copying the pointer shares the same text.

open as a page

When reading a file line by line with std::ifstream in C++, why is while (!file.eof()) wrong, and what loop should you write?

level: middleimportance: must knowfreq 60%

basics

~20 s

eof() only becomes true after a read has already hit the end, so the loop runs once more and processes a failed read. Write while (std::getline(file, line)), which tests each read's result, and parse each line with a std::istringstream.

open as a page

A C++ tool reading integers with std::cin >> n loops forever when the user types a letter; why, and how do you recover the stream?

level: middleimportance: must knowfreq 65%

basics

~20 s

The failed extraction sets failbit and leaves the letter in the input, so every later >> fails immediately without reading. Test the extraction itself, then call std::cin.clear() and std::cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n') to skip the bad line.

open as a page

In a C++ URL builder, why is the pointer from (base + path).c_str() unsafe to give a C API that keeps it?

level: middleimportance: must knowfreq 65%

basics

~20 s

c_str() points into the string's own buffer. The temporary base + path dies at the end of its full-expression, so a C API that stores the pointer later reads freed memory. Keep the std::string alive while C uses it.

open as a page

In C++, why does a std::string_view dangle when it views a temporary std::string or a string that later reallocates?

level: middleimportance: must knowfreq 65%

basics

~20 s

A string_view only borrows characters. A temporary std::string dies at the end of its full-expression, and appending to or reassigning a std::string may move its buffer; either way the view keeps a stale pointer, and reading it is undefined behaviour.

open as a page

In C++, what does std::stoi do with input such as "80abc" or "http", and how should a port parser check it?

level: juniorimportance: should knowfreq 50%

basics

~20 s

std::stoi calls strtol: it skips leading whitespace, converts the longest valid prefix, and returns 80 for "80abc". It throws std::invalid_argument when nothing converts ("http") and std::out_of_range when the value does not fit. Check idx equals the length to reject trailing junk.

open as a page

What is C++17's std::string_view, and why do you pass it by value instead of by const reference?

level: juniorimportance: should knowfreq 60%

basics

~20 s

std::string_view is a read-only, non-owning pointer and length over characters someone else owns. It is two words and trivially copyable, so passing by value is as cheap as a reference without the indirection, and literals convert without allocating.

open as a page

What do C++23 std::print and std::println add over writing a std::format result to std::cout?

level: middleimportance: should knowfreq 45%

basics

~20 s

std::print formats and writes in one call to a C stream, stdout by default, and std::println adds a newline without flushing. Each call writes its whole output as one operation, and Unicode text reaches consoles that need a native Unicode API intact.

open as a page

In a C++ std::format replacement field such as {:*>10.2f}, what do the fill, align, width, precision and type parts do?

level: middleimportance: should knowfreq 48%

basics

~20 s

After the colon, the asterisk is the fill character, > right-aligns, 10 is the minimum field width, .2 is the precision and f selects fixed-point notation, so 15.6249 becomes five asterisks then 15.62. Each part is optional, but the order is fixed.

open as a page

How do you write operator<< and operator>> for a C++ Interval type so it can be printed and parsed with streams?

level: middleimportance: should knowfreq 55%

basics

~20 s

Write them as non-member functions taking the stream by reference and returning it: operator<< takes the Interval by const reference, operator>> by non-const reference. The input operator assigns only after a fully successful read and sets failbit on bad input.

open as a page

When a C++ program builds a std::string URL from many segments, why prefer += and reserve over url = url + segment?

level: middleimportance: should knowfreq 45%

basics

~20 s

url = url + segment builds a new string each pass, copying everything so far: quadratic work and an allocation per pass. url += segment appends in place into spare capacity, and reserve(total) turns the whole build into one allocation.

open as a page

What is the small-string optimization in C++ std::string, and how does it change copying and moving short strings?

level: middleimportance: should knowfreq 55%

basics

~20 s

The small-string optimization stores short text inside the std::string object, so no heap allocation is needed. Short copies allocate nothing, but a short move must copy the characters, and pointers into it do not follow. The capacity is each library's choice.

open as a page

In C++, how does std::string_view::substr differ from std::string::substr, and what goes wrong when find returns npos?

level: middleimportance: should knowfreq 50%

basics

~20 s

std::string::substr returns a new std::string, copying and possibly allocating; std::string_view::substr returns a view into the same characters in constant time. Both throw std::out_of_range when pos exceeds size(). Unchecked, find's npos plus one wraps to 0 and silently selects the whole line.

open as a page

How do you make a C++ Money type printable with std::format, and what must the std::formatter specialization's parse and format members do?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Specialize std::formatter<Money>. Its parse member reads the format specification and returns an iterator to the closing brace, and its const format member writes the value to ctx.out() and returns the end iterator. Inheriting from std::formatterstd::string reuses width, fill and alignment.

open as a page

Why does std::format(tmpl, name, lobby) fail to compile when tmpl is a std::string loaded from a config file, and what do you call instead?

level: seniorimportance: should knowfreq 40%

basics

~10 s

std::format's first parameter is a std::format_string whose constructor is consteval, so it only accepts a compile-time constant it can check. For a runtime template call std::vformat(tmpl, std::make_format_args(name, lobby)) and catch std::format_error.

open as a page

A C++ tool reads and prints millions of lines slowly; what do std::ios::sync_with_stdio(false) and std::cin.tie(nullptr) change, and what can they break?

level: seniorimportance: should knowfreq 50%

basics

~20 s

sync_with_stdio(false) lets the C++ standard streams buffer independently of C stdio, and cin.tie(nullptr) stops std::cin flushing std::cout before every read. Both speed up heavy I/O, but afterwards mixing printf with cout can reorder output and prompts may not appear.

open as a page

Why did C++11 rule out copy-on-write implementations of std::string, and what did that change cost libstdc++ users?

level: seniorimportance: should knowfreq 35%

basics

~20 s

C++11's invalidation rules forbid it: non-const operator[], at, data, begin and end may not invalidate pointers or iterators, but a copy-on-write string must unshare, allocating a new buffer, on that first write. libstdc++ needed a new std::string ABI in GCC 5.

open as a page

Why is passing std::string_view::data() to a C function such as std::atoi or std::fopen a bug in C++?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A string_view ends by its length, so data() need not be null-terminated. A C function scans for '\0' and reads past the view, giving wrong results or undefined behaviour. Pass a terminated std::string copy or use pointer-and-length APIs.

open as a page

How would you lead a C++ codebase's move of its logging and console output from iostreams and printf to std::format?

level: principalimportance: should knowfreq 30%

basics

~20 s

First confirm every supported compiler ships C++20 <format>. Route all output through a wrapper taking std::format_string so call sites stay compile-time checked, plan for changed number text, handle runtime templates and exceptions, and convert module by module behind tests.

open as a page

What rule would you set for std::string_view in a C++ codebase's function parameters, return types and data members, and why?

level: principalimportance: should knowfreq 40%

basics

~20 s

Take std::string_view for read-only parameters; return and store std::string by default. A parameter view is safe because the argument outlives the call; a returned or stored view is not. Allow documented views of *this, static data and short-lived parse results.

open as a page