A format string mixes literal text with directives that control formatted input or output. In C-style functions, those directives must match the types, number, and order of the supplied arguments; mistakes can produce incorrect results or undefined behavior. section 4.3 section 6.1
Format strings can make routine maintenance error-prone:
- For output, swapping a placeholder or argument may compile while producing surprising behavior. A student record illustrates the risk; std::format offers a type-safe alternative, while string streams can become awkward. section 4.3
- For input, specifiers can be difficult to parse: for example, reading a double requires %lf, and a wrong specifier can yield bad data or a crash. Stream extraction uses the destination types instead. section 6.1
Listing 4.7 Using std::format for fine-grained formatting functionality
struct Student {
std::string name;
int age;
double gpa;
Student(const std::string& n, int a, double g) : name(n), age(a), gpa(g) {}
};
int main() {
Student dinah("Dinah", 26, 3.3);
std::cout << std::format("{} is a student aged {} carrying a gpa of
{:0^4}", dinah.name, dinah.age, dinah.gpa) << '\n'; #1
return 0;
}
#1 sprintf-like functionality with type-safe behavior
Compare the student output example with sprintf-style formatting: std::format keeps the placeholders while providing type-safe behavior. section 4.3
Listing 6.1 Using complicated format specifiers to determine conversions
int main() {
const char* str = "3.14159 042 boxes .3";
double pi;
int cats;
int mice;
char buffer[5];
int count = sscanf(str, "%lf%*c%i%s%d", &pi, &cats,
buffer, &mice); #1
if (count != 4) #2
std::cout << "error reading value " << count+1 << '\n';
printf("%f being eaten by %d cats in %s along with %d mice\n",
pi, cats, mice, mice); #3
return 0;
}
The sscanf example shows how several conversion directives can make input parsing hard to read and maintain. section 6.1






