How to Print Leading Zeros with C Output Operator
In C , maintaining control over output formatting is crucial. To achieve this, you can use output operators like the << operator. This guide explores how to use the output operator to print leading zeros in C , similar to the printf() function with the d format specifier.
To accomplish this, consider the following code:
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
This approach uses sprintf() to format the zipCode into a string with leading zeros, which is then output by the << operator. However, it's not ideal due to the extra sprintf() call.
Instead, C provides IO manipulators that offer more flexibility and control. The following code demonstrates their usage:
#include <iostream> #include <iomanip> using namespace std; cout << setw(5) << setfill('0') << zipCode << endl;</p> <p>The setw(5) manipulator sets the field width to 5 characters, ensuring enough space for the zipCode and any leading zeros. The setfill('0') manipulator specifies the fill character as '0', which will be used to pad the field.</p> <p>Alternatively, you can use the fmt library, which simplifies formatting and allows for more expressiveness:</p> <pre class="brush:php;toolbar:false">cout << fmt::format("{0:05d}", zipCode);
Additionally, C 20 introduces the std::format function, providing similar functionality to the fmt library.
However, it's important to note that these IO manipulations affect the global state of the cout object, so subsequent uses of cout will be affected unless you undo the manipulations.
The above is the detailed content of How to Print Leading Zeros in C Using Output Operators?. For more information, please follow other related articles on the PHP Chinese website!