A lightweight, header-only string formatting library for C++ that provides printf-style formatting with a fluent, chainable API.
strformat is a modern C++ string formatting library that:
- Is header-only for simple integration
- Provides printf-style format specifiers
- Uses method chaining for a clean API
- Supports cross-platform development (Windows, Linux)
- Offers locale-independent formatting
- Supports formatting of integers, floating-point numbers, characters, strings, and pointers
- Handles width, precision, alignment, and padding options
- C++17 compatible compiler
- No external dependencies
Simply include the strformat.h header file in your project:
#include"strformat.h"#include"strformat.h"
#include<iostream>intmain() {
// Format to string
std::string result = fmt("Hello, %s! The answer is %d.")
.s("world")
.d(42)
.str();
std::cout << result << std::endl;
// Direct output to stdoutfmt("Hello, %s! The answer is %d.")
.s("world")
.d(42)
.put();
// Direct output to stderrfmt("Error code: %d").d(-1).err();
return0;
}strformat supports the following format specifiers:
%d- 32-bit signed integer%ld- 64-bit signed integer%u- 32-bit unsigned integer%lu- 64-bit unsigned integer%f- Floating-point number%s- String%c- Character%x- Hexadecimal (lowercase)%X- Hexadecimal (uppercase)%o- Octal%p- Pointer
Various formatting options are available:
// Width and paddingfmt("%10d").d(123); // " 123"fmt("%010d").d(123); // "0000000123"fmt("%-10d").d(123); // "123 "// Sign controlfmt("%+d").d(123); // "+123"// Precision for floating-point numbersfmt("%.2f").f(123.456); // "123.46"// Combined optionsfmt("%+10.2f").f(123.456); // " +123.46"You can chain multiple formatting operations:
std::string result = fmt("Name: %s, Age: %d, Balance: $%.2f")
.s("John Doe")
.d(35)
.f(1234.567)
.str();strformat provides several output options:
// Get as string
std::string result = fmt("Value: %d").d(123).str();
// Write to stdoutfmt("Value: %d").d(123).put();
// Write to stderrfmt("Error: %d").d(123).err();
// Write to a FILE pointerFILE* fp = fopen("output.txt", "w");
fmt("Value: %d").d(123).write_to(fp);
fclose(fp);
// Write to a file descriptorfmt("Value: %d").d(123).write_to(fd);
// Get as vector
std::vector<char> buffer = fmt("Value: %d").d(123).vec();
// Append to a vectorfmt("Value: %d").d(123).append_to(&buffer);To disable floating-point support (for smaller footprint):
#defineSTRFORMAT_NO_FP
#include"strformat.h"To disable locale support:
#defineSTRFORMAT_NO_LOCALE
#include"strformat.h"# Using make
make
# Using qmake
./mk.sh
cd _build
makeOpen the Visual Studio solution file strformat.sln and build the project.
This software is distributed under the MIT license.
Copyright (C) 2025 S.Fuchita (soramimi_jp)