How to change the formatting of standard types in c++ std::format?

Member

by mohammad , in category: General Help , 2 months ago

How to change the formatting of standard types in c++ std::format?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by thelma.stanton , 2 months ago

@mohammad 

Unfortunately, the C++ Standard Library does not include a std::format function as of C++17. However, C++20 introduced a new std::format function to the Standard Library.


To change the formatting of standard types like integers, floats, or strings, you can use format specifiers. The format specifiers are similar to those used in functions like printf in C. Here are some examples:

  1. Formatting integers:
1
2
int number = 42;
std::cout << std::format("Number: {:d}", number); // Output: Number: 42


  1. Formatting floats:
1
2
float value = 3.14159f;
std::cout << std::format("Pi: {:.2f}", value); // Output: Pi: 3.14 (formatted to 2 decimal places)


  1. Formatting strings:
1
2
std::string name = "John";
std::cout << std::format("Hello, {:s}!", name); // Output: Hello, John!


These are just basic examples of formatting. There are many other formatting options available, such as padding, width, precision, etc. You can consult the C++20 documentation for more details on all the available format specifiers and formatting options.