Home > Backend Development > C++ > How Can I Print Leading Zeros in C Using the Output Operator?

How Can I Print Leading Zeros in C Using the Output Operator?

Patricia Arquette
Release: 2024-12-01 08:32:10
Original
425 people have browsed it

How Can I Print Leading Zeros in C   Using the Output Operator?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template