Home >Backend Development >C++ >How Can I Format Output Using the C Output Operator (`

How Can I Format Output Using the C Output Operator (`

Patricia Arquette
Patricia ArquetteOriginal
2024-12-07 09:18:14354browse

How Can I Format Output Using the C   Output Operator (`

Formatting Output Using the Output Operator (<<)

You seek a method to format output using the output operator (<<) in C . While you could utilize printf, you favor the use of the output operator.

Solution

The following code effectively formats output using the output operator:

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
  int zipCode = 12345;
  cout << setw(5) << setfill('0') << zipCode << endl;

  return 0;
}</h2>
<p>This code utilizes IO manipulators to control padding:</p>
<ul>
<li>setw(width) sets the field width to five.</li>
<li>setfill(fillchar) sets the fill character to '0'.</li>
</ul>
<p>This results in the ZIP code being formatted with leading zeros: 012345.</p>
<h2>Alternative Approaches</h2>
<p>If you prefer a more concise approach, you can use the fmt library:</p>
<pre class="brush:php;toolbar:false">cout << fmt::format("{:05d}", zipCode);

In C 20 and later, the std::format functionality is available:

cout << std::format("{:05d}", zipCode);

Considerations

Note that these IO manipulators affect the global state of cout. Subsequent usages of cout will be impacted unless the manipulations are explicitly undone.

For negative numbers, use std::internal to place the fill character between the sign and the magnitude:

cout << internal << setw(5) << setfill('0') << zipCode << endl;

You can safely assume that all ZIP codes are non-negative, but this is an assumption nonetheless.

The above is the detailed content of How Can I Format Output Using the C Output Operator (`. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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