Print Leading Zeros with C Output Operator
The C output operator (<<) provides a convenient way to format and print data. To print leading zeros, you can use the setw() and setfill() manipulators.
#include#include using namespace std; int main() { // Print a 5-digit ZIP code with leading zeros int zipCode = 12345; cout << setw(5) << setfill('0') << zipCode << endl; // Output: "012345" return 0; } The setw() manipulator sets the minimum field width of the field. In this case, it sets the minimum width to 5 characters. The setfill() manipulator sets the character used to fill the field. In this case, it sets the fill character to '0', which results in leading zeros.
Additional IO Manipulators:
- std::setw(width): Sets the field width.
- std::setfill(fillchar): Sets the field fill character.
- std::setiosflags(align): Sets the field alignment (left or right).
Note:
- These manipulators affect the global state of the cout object. If you change the field settings, it can affect subsequent uses of cout.
- Consider using the fmt library (https://github.com/fmtlib/fmt) for formatting output, which simplifies the process and provides more options.
- C 20 includes std::format and C 23 includes std::print, which offer convenient formatting options similar to fmt.
The above is the detailed content of How Can I Print Leading Zeros in C Using the Output Operator?. For more information, please follow other related articles on the PHP Chinese website!