C++ output used to force a choice. printf is fast but type-unsafe. std::cout is type-safe but verbose, stateful, and slow by default. C++20 introduced std::format and C++23 added std::print and std::println, which give you Python-style format strings with compile-time checking and direct output to stdout. This guide covers the syntax, the format specification grammar, custom formatters, runtime format strings, and the edge cases that cause real bugs.
Quick Takeaways
- std::print and std::println (header
<print>) write formatted text straight tostdout. std::println appends a newline. - std::format (header
<format>) returns a std::string. Format strings are validated at compile time. - Format specs like
{:>8.2f}replace sticky iostream manipulators. No state leaks between calls. - Teach custom types to the system by specializing std::formatter<T>.
Syntax Breakdown
std::print and std::println
Both functions live in <print>. They take a format string followed by arguments.
#include <print>
int main() {
std::print("Hello, {}!\n", "C++23"); // no automatic newline
std::println("Sum: {}", 2 + 3); // newline appended
}
Output:
Hello, C++23!
Sum: 5
Each {} is a replacement field. The compiler matches fields to arguments in order. If the counts differ, the program fails to compile. This is the main safety gain over printf.
To write to another stream, pass a FILE* as the first argument:
#include <print>
#include <cstdio>
void report_error(int code) {
std::println(stderr, "Error code: {}", code);
}
An overload for std::ostream& also exists. That lets you route formatted output into streams such as std::ostringstream.
Compile-Time Format String Checking
The format string parameter is std::format_string<Args…>, whose constructor is consteval. The compiler parses the format string while compiling.
std::println("{} {}", 1); // compile error: too few arguments
std::println("{:d}", "text"); // compile error: 'd' is invalid for strings
std::println("{", 1); // compile error: unterminated field
Errors surface at build time, not at 3 a.m. in production.
The Format Specification Grammar
Inside a replacement field, everything after the colon is the format spec:
{ [arg-id] : [[fill]align] [sign] [#] [0] [width] [.precision] [L] [type] }
| Component | Options | Example | Result |
|---|---|---|---|
| align | < left, > right, ^ center |
{:^7} |
" 42 " |
| fill | any char before align | {:*>6} |
"****42" |
| sign | +, -, space |
{:+d} |
+42 |
| # | alternate form (prefixes) | {:#x} |
0x2a |
| 0 | zero-pad numerics | {:05d} |
00042 |
| precision | digits or max chars | {:.2f} |
3.14 |
| L | locale-specific output | {:L} |
1,234,567 (locale-dependent) |
| type | d x X b o c s f e g a p ? |
{:b} |
101010 |
Applying Specs to Numbers
#include <print>
int main() {
double pi = 3.14159265;
int n = 255;
std::println("{:.2f}", pi); // 3.14
std::println("[{:>8}]", n); // [ 255]
std::println("[{:<8}]", n); // [255 ]
std::println("[{:^8}]", n); // [ 255 ]
std::println("{:08.3f}", pi); // 0003.142
std::println("{:#x} {:#b} {:#o}", n, n, n); // 0xff 0b11111111 0377
std::println("{:e}", 12345.678); // 1.234568e+04
}
Each call is independent. Unlike std::hex on a stream, nothing persists after the call returns.
Positional and Dynamic Arguments
You can reorder arguments with indices. You can also pass width or precision as arguments.
#include <print>
int main() {
std::println("{1} {0}", "world", "Hello"); // Hello world
std::println("[{:>{}}]", "hi", 6); // [ hi]
std::println("{:.{}f}", 3.14159265, 3); // 3.142
}
Do not mix automatic ({}) and manual ({0}) indexing in one format string. That is ill-formed. Use {{ and }} to print literal braces.
Booleans, Characters, and Debug Output
#include <print>
int main() {
std::println("{}", true); // true
std::println("{:d}", true); // 1
std::println("{}", 'A'); // A
std::println("{:d}", 'A'); // 65
std::println("{:?}", "tab\there"); // "tab\there" (C++23 debug format)
}
The ? type produces an escaped, quoted representation. It is useful for logging strings with control characters.
std::format: Strings Without Streams
std::format has the same grammar as std::print. It returns a std::string.
#include <format>
#include <string>
#include <print>
int main() {
std::string row = std::format("{:<10}|{:>8.2f}", "Widget", 19.5);
std::println("{}", row); // Widget | 19.50
}
Avoiding Allocations with format_to
std::format allocates a new string every call. In hot paths, write into an existing buffer with std::format_to, std::format_to_n, or measure first with std::formatted_size.
#include <format>
#include <iterator>
#include <string>
#include <print>
int main() {
std::string out;
out.reserve(64);
for (int i = 0; i < 3; ++i) {
std::format_to(std::back_inserter(out), "[{}]", i);
}
std::println("{}", out); // [0][1][2]
char buf[8];
auto r = std::format_to_n(buf, sizeof(buf) - 1, "{}", 1234567890);
*r.out = '\0';
std::println("{} (needed {})", buf, r.size); // 1234567 (needed 10)
}
std::format_to_n truncates safely and reports the full required size in r.size.
Formatting Containers, Tuples, and Time
C++23 adds range formatting (P2286). Standard containers, pairs, and tuples print without extra code. This requires a standard library that has implemented it, so check your vendor’s status page.
#include <map>
#include <print>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
std::map<std::string, int> m{{"a", 1}, {"b", 2}};
std::pair<int, std::string> p{7, "x"};
std::println("{}", v); // [1, 2, 3]
std::println("{}", m); // {"a": 1, "b": 2}
std::println("{}", p); // (7, "x")
}
C++20 also added chrono formatting through the same system:
#include <chrono>
#include <print>
int main() {
auto now = std::chrono::system_clock::now();
std::println("{:%Y-%m-%d}", now); // e.g. 2026-11-29
}
Custom Types with std::formatter
To print your own types, specialize std::formatter<T>. You implement two members: parse() reads the spec, and format() writes the output.
#include <format>
#include <print>
struct Point {
double x;
double y;
};
template <>
struct std::formatter<Point> {
// Accept only the empty spec: "{}"
constexpr auto parse(std::format_parse_context& ctx) {
return ctx.begin();
}
auto format(const Point& p, std::format_context& ctx) const {
return std::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y);
}
};
int main() {
Point p{1.5, 2.5};
std::println("Origin offset: {}", p); // Origin offset: (1.5, 2.5)
}
Mark format() as const. The standard formattability requirements demand it. If you need a custom spec such as {:polar}, parse it in parse() and return an iterator to the closing }.
For a type that wraps another formattable value, inherit from the underlying formatter. That reuses all its specs (width, fill, precision) for free:
struct Meters { double v; };
template <>
struct std::formatter<Meters> : std::formatter<double> {
auto format(const Meters& m, std::format_context& ctx) const {
auto out = std::formatter<double>::format(m.v, ctx);
return std::format_to(out, " m");
}
};
// std::println("{:.2f}", Meters{3.14159}); -> 3.14 m
Runtime Format Strings
A format string must be a compile-time constant by default. That blocks strings loaded from config files or translation catalogs. Use std::vformat with std::make_format_args:
#include <format>
#include <print>
#include <string>
int main() {
std::string fmt = "Hello, {}!"; // imagine this came from a file
std::string name = "Ada";
std::string s = std::vformat(fmt, std::make_format_args(name));
std::println("{}", s); // Hello, Ada!
}
std::make_format_args takes lvalue references. Passing a temporary is ill-formed in C++23 because the args object stores references and would dangle. A malformed runtime string throws std::format_error. C++26 adds std::runtime_format, which lets you pass a runtime string straight to std::format and std::print.
Unicode, Locale, and Stream Behavior
Locale. std::format is locale-independent by default. {} on 1234.5 always prints 1234.5. Add the L specifier to opt in to the active locale.
Unicode. std::print is Unicode-aware. On Windows, if the literal encoding is UTF-8 (compile with /utf-8 on MSVC) and stdout is a terminal, it uses the native Unicode console API. That avoids the classic mojibake from code pages.
Interleaving with iostream. std::print writes through the C FILE* for stdout. With the default std::ios::sync_with_stdio(true), output mixes correctly with std::cout. If you call sync_with_stdio(false), ordering between the two is no longer guaranteed. Pick one output path per stream.
Flushing. std::println does not flush. Terminals line-buffer stdout. Pipes and files fully buffer it. Call std::fflush only when you need the data visible immediately.
printf vs iostream vs std::print
| Feature | printf | std::cout | std::print |
|---|---|---|---|
| Type safety | None | Yes | Yes |
| Format string check | Compiler warning (non-standard) | N/A | Compile-time (standard) |
| Custom types | No | operator<< | std::formatter |
| Persistent state | None | Sticky manipulators | None |
| Locale default | C locale | Global locale | Locale-independent |
| Positional args | POSIX extension | No | Yes ({1}) |
| Verbosity | Low | High | Low |
| Typical speed | Fast | Slower | Fast, usually beats iostream |
Treat speed claims as workload-dependent and benchmark your own case. std::print formats into a buffer and performs a small number of writes. std::cout chains many operator<< calls.
Bad Code vs. Good Code
Anti-pattern: Sticky Stream State
// BAD: manipulators mutate the stream permanently
std::cout << std::fixed << std::setprecision(2) << price << '\n';
std::cout << std::hex << 255 << '\n';
std::cout << 42 << '\n'; // surprise: prints 2a, not 42
// GOOD: each call carries its own spec
std::println("{:.2f}", price);
std::println("{:x}", 255);
std::println("{}", 42); // 42
Anti-pattern: Concatenating Strings by Hand
// BAD: temporary strings, manual conversion, easy to misformat
std::string line = "User " + std::to_string(id) + " scored "
+ std::to_string(score) + "%";
// GOOD: one expression, one allocation, checked at compile time
std::string line = std::format("User {} scored {}%", id, score);
Anti-pattern: Flushing Every Line
// BAD: std::endl flushes on every iteration
for (int i = 0; i < 100000; ++i) {
std::cout << i << std::endl;
}
// GOOD: no forced flush
for (int i = 0; i < 100000; ++i) {
std::println("{}", i);
}
Anti-pattern: Unchecked Runtime Format Strings
// BAD: user input used as a format string
std::string s = std::vformat(user_input, std::make_format_args(value));
// A malformed string throws std::format_error; the exception is unhandled here.
// GOOD: fixed format, user data as an argument
std::println("Input was: {}", user_input);
Edge Cases and Compiler Support
- char pointers and
{:p}. Theptype accepts onlyconst void*ornullptr_t. Cast first:static_cast<const void*>(ptr). - char vs int.
std::println("{}", 'A')printsA. Use{:d}or cast to print65. - Missing header. std::print needs
<print>, not<format>alone. - Argument lifetime. Never store the result of std::make_format_args beyond the full expression that created it.
- Compiler support.
<format>ships in GCC 13+, Clang 17+ with a recent libc++, and MSVC 19.29+.<print>ships in GCC 14+, Clang 18+ with libc++ 18, and MSVC 19.37+ (Visual Studio 2022 17.7). Compile with-std=c++23or/std:c++latest.
For older toolchains, the open-source {fmt} library is the reference implementation. Its API is nearly identical (fmt::print, fmt::format), so migration is a namespace swap.
FAQ
Which header do I need for std::print?
Include <print>. It declares std::print and std::println. For std::format, std::format_to, and std::formatter, include <format>.
Is std::print faster than std::cout?
In most workloads, yes. std::print formats into a buffer and writes in large chunks. std::cout performs many small operator<< calls and carries locale and stream-state overhead. Performance depends on the standard library, so benchmark your own case.
How do I use a format string that is only known at runtime?
Use std::vformat with std::make_format_args, which throws std::format_error on a bad string. In C++26, wrap the string in std::runtime_format.
Which compilers support std::print?
GCC 14 and later, Clang 18 and later with libc++ 18, and MSVC 19.37 (Visual Studio 2022 17.7) and later. Check your standard library’s release notes for partial gaps such as range formatting.




