Format Output with Leading Zeros in C
In C , formatting output is crucial to display data in a specific way. One common scenario is to print leading zeros, similar to how printf handles it with d. While using printf is an option, you may prefer the C stream output operator (<<).
One option to achieve leading zeros is by concatenating a formatted string using sprintf with your output operator, as shown below:
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
However, there's a cleaner solution using IO manipulators:
#include <iomanip> using namespace std; cout << setw(5) << setfill('0') << zipCode << endl; // or without 'using namespace std;' std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;</p> <p>setw(width) sets the field width, while setfill(char) specifies the character used to fill the remaining space. In this case, '0' is used to add leading zeros.</p> <p>Note that these manipulators affect the global state of the cout object. To avoid unintended effects in later uses, you should undo them by resetting the flags.</p> <p>If you prefer concise formatting, consider using the fmt library:</p> <pre class="brush:php;toolbar:false">cout << fmt::format("{:05d}", zipCode);
C 20 and later have built-in support for std::format, and C 23 introduces std::print, providing even more convenient options for formatted output.
For non-negative numbers like ZIP codes, the above code will suffice. However, if you need to handle negative numbers, add std::internal to place the fill character between the sign and the magnitude:
cout << internal << setw(5) << setfill('0') << zipCode << endl;
The above is the detailed content of How Can I Format Output with Leading Zeros in C ?. For more information, please follow other related articles on the PHP Chinese website!