Home > Backend Development > C++ > How Can I Format Output with Leading Zeros in C ?

How Can I Format Output with Leading Zeros in C ?

DDD
Release: 2024-12-04 21:44:15
Original
861 people have browsed it

How Can I Format Output with Leading Zeros in C  ?

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;
Copy after login

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);
Copy after login

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;
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template