In C++20 use std::format from <format>: it returns a std::string, like sprintf without the buffer. std::format("{} scored {:.1f}", name, avg) fills each {} in order, and the spec after the colon sets width, fill, precision and base. To print a double with full precision, std::format("{}", x) gives the shortest text that reads back as the same value.
For years the C++ answer to "how do I sprintf into a std::string?" was a choice between std::ostringstream, which is type-safe but wordy and leaves settings stuck on the stream, and snprintf, which is compact but checks nothing. C++20's std::format takes the best of both: Python-style placeholders, a compact spec, and types checked when the code compiles. The sections below cover std::format, printing a double without losing digits, the stream and snprintf answers you still meet in older code, formatting your own types, and format strings chosen at run time. Each example runs on this page: hit Run, then edit the code and run it again.
1std::format (C++20)Recommended
std::format(fmt, args...) returns a new std::string. Each {} in fmt takes the next argument; a number such as {1} picks one by position. After a colon comes the spec, in this order: fill character, alignment (<, > or ^), sign, #, 0 padding, width, .precision and type (f, e, g, x, b, o…). So {:*^9} centres in 9 columns padded with stars, and {:08.3f} is 3 decimals, zero-padded to 8 characters.
The format string is checked at compile time: a spec that doesn't fit the argument's type, or more placeholders than arguments, is a compile error rather than garbage at run time. std::format_to writes into an iterator instead, which appends to a string you already have without a temporary.
#include <format> #include <iostream> #include <iterator> #include <string> int main() { std::string name = "Ada"; int score = 42; double ratio = 0.8125; // {} takes the next argument and formats it the default way std::string s = std::format("{} scored {} ({}%)", name, score, ratio * 100); std::cout << s << '\n'; // A width alone: strings align left, numbers right std::cout << std::format("[{:6}] [{:6}]\n", name, score); // After the colon: fill, align, width, sign, precision, type std::cout << std::format("[{:>6}] [{:<6}] [{:^7}]\n", name, name, name); std::cout << std::format("[{:*^9}] [{:08.3f}] [{:+}]\n", name, ratio, score); // Zero padding and a fixed number of decimals std::cout << std::format("{:05} {:.2f}\n", 42, 3.14159); // Other bases; # adds the 0x / 0b / 0 prefix std::cout << std::format("{:x} {:#x} {:#010x} {:#b} {:o}\n", 255, 255, 255, 5, 8); // Numbered arguments can repeat and change order std::cout << std::format("{1} before {0}, {1} again\n", "a", "b"); // Literal braces are doubled std::cout << std::format("{{}} is a placeholder, {} is a value\n", score); // The width can come from an argument too int width = 6; std::cout << std::format("[{:>{}}]\n", score, width); // format_to appends to an existing string instead of making a new one std::string log = "log:"; for (int i = 1; i <= 3; ++i) { std::format_to(std::back_inserter(log), " #{}={:.1f}", i, i * 0.5); } std::cout << log << '\n'; }
Output
A double with plain {} prints as few digits as it needs: 81.25%, not 81.250000. With a width alone, strings align left and numbers right ([Ada ] [ 42]); >, < and ^ override that. {:05} zero-pads to 00042 and {:.2f} gives 3.14. Watch the rounding in [0000.812]: 0.8125 is exactly halfway, and std::format, like printf, rounds an exact tie to the even digit. The # flag gives 0xff and 0b101, and {:#010x} pads after the prefix: 0x000000ff. Mixing {} and {0} in one string is not allowed; section 6 shows the error. In C++23, std::println from <print> formats and prints in one call; this page compiles as C++20, hence std::cout << std::format(…). To build a string from an int alone, see converting an int to a string.
2Printing a double with full precision
std::cout prints a double with 6 significant digits, so 0.1 + 0.2 shows as 0.3 and two different values look equal. To see the real value, use std::format's {}, which prints the shortest decimal text that converts back to exactly the same double. With streams, set the precision to std::numeric_limits<double>::max_digits10: 17 significant digits are always enough to round-trip, though sometimes more than needed.
#include <format> #include <iomanip> #include <iostream> #include <limits> #include <string> int main() { double x = 0.1 + 0.2; // cout shows 6 significant digits by default, which hides the error std::cout << "cout default: " << x << '\n'; // std::format's {} prints the shortest text that reads back // as exactly the same double std::cout << "format {}: " << std::format("{}", x) << '\n'; std::cout << "round trip: " << std::boolalpha << (std::stod(std::format("{}", x)) == x) << '\n'; // iostreams: max_digits10 (17 for double) always round-trips, // but it may print more digits than the shortest form needs constexpr int max_digits = std::numeric_limits<double>::max_digits10; std::cout << "max_digits10: " << max_digits << '\n'; std::cout << std::setprecision(max_digits); std::cout << "precision 17: " << x << ' ' << 0.1 << '\n'; // digits10 (15) is NOT enough: x and 0.3 print the same constexpr int digits10 = std::numeric_limits<double>::digits10; std::cout << std::setprecision(digits10); std::cout << "precision 15: " << x << ' ' << 0.3 << '\n'; // The double nearest 0.1 is not 0.1; more decimals show it std::cout << "{:.20f}: " << std::format("{:.20f}", 0.1) << '\n'; // std::to_string always uses 6 decimals (like %f) std::cout << "to_string: " << std::to_string(x) << ' ' << std::to_string(1e-7) << '\n'; }
Output
The default cout shows 0.3, while std::format("{}", x) shows 0.30000000000000004, and std::stod reads it back to the same bits (round trip: true). Precision 17 also round-trips but prints 0.10000000000000001 for 0.1, where the shortest form is just 0.1. The common answer digits10 (15) is not enough: it prints 0.3 0.3 for two different values. {:.20f} shows why: the stored value is 0.10000000000000000555, the nearest double to 0.1. std::to_string always uses %f, 6 decimals, so it prints 0.000000 for 1e-7; C++26 changes it to match std::format, but this page compiles as C++20. To compare such values, see comparing floating-point numbers.
3Before C++20: std::ostringstream and manipulators
Without std::format, the type-safe way to build a formatted string is to write into a std::ostringstream with << and take .str() at the end. The manipulators from <iomanip> do the formatting: std::setw for width, std::setfill for the pad character, std::left / std::right, std::fixed with std::setprecision for decimals, and std::hex. The catch is that most of them change the stream for good.
#include <iomanip> #include <iostream> #include <sstream> #include <string> int main() { // Before C++20: build the text in an ostringstream, then take .str() std::ostringstream out; out << std::fixed << std::setprecision(2); out << std::left << std::setw(6) << "tea" << std::right << std::setw(7) << 3.5 << '\n'; out << std::left << std::setw(6) << "cake" << std::right << std::setw(7) << 12.0 << '\n'; std::string table = out.str(); std::cout << table; // Zero padding: setfill sets the pad character std::ostringstream id; id << "ID-" << std::setfill('0') << std::setw(5) << 42; std::cout << id.str() << '\n'; // Gotcha 1: setw applies to the next item only... std::cout << '[' << std::setw(4) << 1 << ']' << '[' << 2 << "]\n"; // ...but hex, fixed, setprecision and setfill stick to the stream std::cout << std::hex << 255 << ' ' << 255 << '\n'; std::cout << 16 << " is still hex\n"; std::cout << std::dec; // Gotcha 2: so save the state and restore it when you are done std::ios_base::fmtflags flags = std::cout.flags(); std::streamsize precision = std::cout.precision(); std::cout << std::fixed << std::setprecision(1) << 2.375 << '\n'; std::cout.flags(flags); std::cout.precision(precision); std::cout << 2.375 << " after restoring\n"; }
Output
std::fixed turns setprecision(2) into "2 decimals", so the table prints 3.50 and 12.00; without fixed the precision counts significant digits instead. The gotchas are in the output: [ 1][2] shows setw padding only the next item, while std::hex stays on, so a later 16 prints as 10 is still hex. On std::cout that leaks into every line the rest of the program prints, which is why the last block saves flags() and precision() and restores them: 2.375 after restoring is back to the default. Writing to a fresh ostringstream, as the first two blocks do, avoids the problem.
4snprintf into a std::string
The literal answer to "sprintf for std::string" is std::snprintf with a size check. Called with a null buffer and size 0, it writes nothing and returns how many characters the result needs, so you can size a std::string exactly and write into s.data(). Never use plain sprintf: it has no size, so a long value overruns the buffer.
#include <cstdio> #include <iostream> #include <stdexcept> #include <string> // The sprintf answer, made safe: measure first, then write into the string template <typename... Args> std::string string_printf(const char* fmt, Args... args) { // With a null buffer, snprintf only returns the length it would write int n = std::snprintf(nullptr, 0, fmt, args...); if (n < 0) { throw std::runtime_error("bad format string"); } std::string s(n, '\0'); // n + 1 leaves room for the '\0' snprintf always writes; // a std::string keeps one past size() for exactly that std::snprintf(s.data(), n + 1, fmt, args...); return s; } int main() { std::string name = "Ada"; // %s wants a C string: pass name.c_str(), never the std::string itself std::string s = string_printf("%s is %d, %.2f%% done", name.c_str(), 36, 87.5); std::cout << s << " (" << s.size() << " chars)\n"; // Width, zero padding and hex work as in C std::cout << string_printf("[%-6s] [%06.2f] [%#x]", "ab", 3.14159, 255) << '\n'; // size_t is %zu, long long is %lld: the wrong one is undefined behaviour std::size_t count = 3; long long big = 9000000000LL; std::cout << string_printf("%zu items, %lld bytes", count, big) << '\n'; // A fixed buffer: snprintf truncates and reports the length it wanted char buf[8]; int wanted = std::snprintf(buf, sizeof buf, "value=%d", 123456); bool truncated = wanted >= static_cast<int>(sizeof buf); std::cout << '[' << buf << "] wanted " << wanted << ", truncated: " << std::boolalpha << truncated << '\n'; }
Output
The helper prints Ada is 36, 87.50% done (22 chars): the string is exactly as long as the text, with no stray \0. A literal % is written %%. The fixed 8-byte buffer keeps value=1, 7 characters plus the terminator, and the return value 12 tells you the full text did not fit. What printf-style functions cannot do is check types: passing a std::string to %s without .c_str(), or an int to %f, compiles and is undefined behaviour at run time. GCC only warns about it with -Wformat, which this page does not turn on. That is the main reason to prefer std::format, which rejects the same mistakes at compile time. For more on c_str(), see converting a string to a char pointer.
5Formatting your own types with std::formatter
std::format works with any type that has a std::formatter specialization. The shortest way to write one is to inherit from an existing formatter: its parse already reads the spec, so {:.1f} or {:>7} keep working on your type, and you only write format. Here a Point reuses the double formatter for each coordinate, and an enum class reuses the string_view formatter for its name.
#include <format> #include <iostream> #include <string> #include <string_view> struct Point { double x; double y; }; enum class Color { red, green, blue }; // Inherit the double formatter: its parse() reads specs such as .1f, // and format() applies them to each coordinate template <> struct std::formatter<Point> : std::formatter<double> { auto format(const Point& p, std::format_context& ctx) const { auto out = std::format_to(ctx.out(), "("); ctx.advance_to(out); out = std::formatter<double>::format(p.x, ctx); out = std::format_to(out, ", "); ctx.advance_to(out); out = std::formatter<double>::format(p.y, ctx); return std::format_to(out, ")"); } }; // Inherit the string_view formatter: width and alignment work on the name template <> struct std::formatter<Color> : std::formatter<std::string_view> { auto format(Color c, std::format_context& ctx) const { std::string_view name = c == Color::red ? "red" : c == Color::green ? "green" : "blue"; return std::formatter<std::string_view>::format(name, ctx); } }; int main() { Point p{3.14159, -2.5}; std::cout << std::format("p = {}\n", p); std::cout << std::format("p = {:.1f}\n", p); std::cout << std::format("[{:>7}] [{:<7}] [{}]\n", Color::red, Color::green, Color::blue); }
Output
The same Point prints as p = (3.14159, -2.5) with {} and p = (3.1, -2.5) with {:.1f}, because the inherited parse stored the spec and each call to formatter<double>::format applies it. The enum gets width and alignment for free: [ red] and [green ]. The format member must be const, and ctx.advance_to tells the context where the output has reached before the inherited format writes more. Without a formatter, passing a Point to std::format is a compile error. For more ways to name enum values, see converting an enum to a string.
6Format strings chosen at run time: std::vformat
Because std::format checks its format string at compile time, the string must be a constant. Pass a std::string variable and GCC stops with error: call to consteval function 'std::basic_format_string<char, int>(pattern)' is not a constant expression. For a pattern loaded at run time (a translation, a config value) use std::vformat with the arguments packed by std::make_format_args. The check then happens when the call runs, and a bad pattern throws std::format_error.
#include <format> #include <iostream> #include <string> int main() { // A format string that is only known at run time, e.g. read from a // config file. std::format(pattern, ...) would not compile here: // std::format checks its format string at compile time. std::string pattern = "{} has {} unread messages"; std::string user = "ada"; int unread = 3; // std::vformat takes a runtime string; make_format_args packs the // arguments, which must be variables (lvalues), not temporaries auto args = std::make_format_args(user, unread); std::cout << std::vformat(pattern, args) << '\n'; // Mistakes in a runtime pattern are found only when it runs: // std::vformat throws std::format_error std::string bad_patterns[] = {"{} has {} unread {}", "{:d}", "{0} {}"}; for (const std::string& bad : bad_patterns) { try { std::cout << std::vformat(bad, args) << '\n'; } catch (const std::format_error& e) { std::cout << "format_error: " << e.what() << '\n'; } } }
Output
The good pattern prints ada has 3 unread messages. The three bad ones each throw: a third placeholder with only two arguments gives format error: invalid arg-id in format string, {:d} on a string gives format error: failed to parse format-spec, and mixing {0} with {} gives format error: conflicting indexing style in format string. With a literal pattern and std::format, the same mistakes fail to compile instead. make_format_args takes its arguments by reference, so pass variables, not temporaries such as user + "!", and use the result in the same statement or while those variables live.
7Which should you use?
| Method | Type-safe | Standard | Best for |
|---|---|---|---|
| std::format | Compile time | C++20 | Almost everything |
| std::format_to | Compile time | C++20 | Appending to an existing string or buffer |
| std::vformat | At run time | C++20 | Format strings loaded at run time |
| std::ostringstream + <iomanip> | Yes | Any | Code that must build before C++20 |
| std::snprintf | No | C | C APIs, fixed buffers, old code |
| std::to_string | Yes | C++11 | Integers only; doubles get 6 decimals |
Frequently asked questions
How do I format a double to 2 decimal places in C++?
Use std::format("{:.2f}", x), which returns a std::string, so 3.14159 becomes 3.14. With streams the same is std::cout << std::fixed << std::setprecision(2) << x; leave out std::fixed and setprecision(2) means 2 significant digits instead. A value exactly halfway, such as 0.8125 at 3 decimals, rounds to the even digit and prints 0.812.
How do I print a double with full precision in C++?
std::format("{}", x) prints the shortest text that reads back as the same double: 0.1 + 0.2 prints 0.30000000000000004. With streams, use std::setprecision(std::numeric_limits<double>::max_digits10), which is 17 and always round-trips. digits10 (15) is not enough: it prints 0.3 for both 0.1 + 0.2 and 0.3.
Is there a sprintf that returns a std::string?
Yes, since C++20: std::format is exactly that, with {} placeholders instead of %d and %s and type checks at compile time. Before C++20, call std::snprintf(nullptr, 0, fmt, args...) to get the length, create a std::string of that size, and snprintf into s.data() with size n + 1. The {fmt} library, which std::format is based on, gives the same API to older compilers.
Why does std::format not compile with a std::string as the format?
std::format checks the format string at compile time, so it must be a string literal or another constant expression. For a pattern only known at run time, call std::vformat(pattern, std::make_format_args(a, b)). Errors in that pattern then throw std::format_error when the call runs, so catch it if the pattern comes from outside the program.
How do I zero-pad a number in C++?
Put 0 and the width in the spec: std::format("{:05}", 42) gives 00042, and std::format("{:#010x}", 255) gives 0x000000ff, padded after the prefix. With streams, std::setfill('0') << std::setw(5) << 42 does the same, but setfill stays on the stream while setw applies to the next item only.
Can I use std::print in C++?
std::print and std::println from <print> are C++23. They take the same format strings as std::format and write straight to the console, so std::println("{} = {}", name, value) replaces std::cout << std::format(...). This page compiles as C++20, so its examples use std::cout << std::format(...), which prints the same text.