C++ Create String with Format Specifier
In C++, you can use format specifiers to create strings with specific formats, similar to the printf
function in C. The std::format
library, available in C++20 and later, provides a powerful and flexible way to format strings.
Basic Usage
The std::format
library uses the std::format
function to create formatted strings. The function takes a format string and a variable number of arguments, similar to printf
.
#include
#include
int main() {
int age = 30;
std::string name = "John Doe";
std::string formatted_string = std::format("Hello, my name is {} and I am {} years old.", name, age);
std::cout << formatted_string << std::endl; // Output: Hello, my name is John Doe and I am 30 years old.
return 0;
}
Format Specifiers
The std::format
library uses the following format specifiers:
{}
: Placeholder for an argument.{n}
: Placeholder for the nth argument.{n:specifier}
: Placeholder for the nth argument with a specific format specifier.
Here are some common format specifiers:
d
: Decimal integer.f
: Floating-point number.s
: String.c
: Character.p
: Pointer address.x
: Hexadecimal integer.o
: Octal integer.
Example: Formatting Numbers
#include
#include
int main() {
double pi = 3.14159265359;
int number = 12345;
// Formatting a floating-point number with 2 decimal places
std::string formatted_pi = std::format("Pi: {:.2f}", pi);
// Formatting an integer with leading zeros
std::string formatted_number = std::format("Number: {:05d}", number);
std::cout << formatted_pi << std::endl; // Output: Pi: 3.14
std::cout << formatted_number << std::endl; // Output: Number: 01234
return 0;
}
Example: Formatting Strings
#include
#include
int main() {
std::string name = "John Doe";
std::string message = "Welcome to C++ formatting!";
// Formatting a string with uppercase letters
std::string formatted_name = std::format("Name: {}", std::format_to(std::string(), "{:10s}", name));
// Formatting a string with a specific width
std::string formatted_message = std::format("{:30s}", message);
std::cout << formatted_name << std::endl; // Output: Name: John Doe
std::cout << formatted_message << std::endl; // Output: Welcome to C++ formatting!
return 0;
}
Conclusion
The std::format
library provides a powerful and flexible way to format strings in C++. It allows you to create custom formatting for various data types, including numbers, strings, and pointers. By using format specifiers, you can control the output of your strings, ensuring they are displayed in the desired format.