Language: CPP
CLI/Utils
fmt was created by Victor Zverovich to provide an efficient and safe formatting library for C++ that combines the convenience of Python’s str.format with C++ type safety. It became widely used and is the basis for C++20's std::format.
fmt is a modern C++ library for safe and fast string formatting. It provides a type-safe alternative to printf and std::stringstream, supporting Python-like format strings and compile-time checks.
sudo apt install libfmt-devbrew install fmtDownload and build from https://github.com/fmtlib/fmtfmt allows formatting strings using Python-like replacement fields with `{}`. It supports compile-time checking, positional arguments, named arguments, width, alignment, precision, and localization.
#include <fmt/core.h>
#include <iostream>
int main() {
std::string name = "Alice";
int age = 30;
std::cout << fmt::format("{} is {} years old", name, age) << std::endl;
return 0;
}Formats a string using `{}` placeholders for variables.
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("{name} is {age} years old", fmt::arg("name", "Bob"), fmt::arg("age", 25)) << std::endl;
return 0;
}Demonstrates using named arguments for string formatting.
#include <fmt/core.h>
#include <iostream>
int main() {
double pi = 3.14159265;
std::cout << fmt::format("Pi rounded to 2 decimals: {:.2f}", pi) << std::endl;
return 0;
}Formats a floating-point number with 2 decimal places.
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("|{:<10}|{:^10}|{:>10}|", "left", "center", "right") << std::endl;
return 0;
}Shows left, center, and right alignment within a fixed width.
#include <fmt/core.h>
#include <fstream>
int main() {
std::ofstream file("output.txt");
fmt::print(file, "Hello {}!\n", "World");
return 0;
}Writes a formatted string directly to a file.
#include <fmt/compile.h>
#include <iostream>
int main() {
std::cout << fmt::format(FMT_COMPILE("Hello {}!"), "World") << std::endl;
return 0;
}Demonstrates compile-time checked formatting for better performance and safety.
Prefer fmt::format over printf for type safety.
Use named arguments for clarity in long format strings.
Leverage compile-time formatting for performance-critical code.
Use fmt::print for simple output to console or files.
Combine fmt with logging libraries to format log messages safely.