Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What directive can I give a stream to print leading zeros on a number in C++?

I know how to cause it to be in hex:

unsigned char myNum = 0xA7;
clog << "Output: " std::hex << int(myNum) << endl;
// Gives:
//   Output: A7

Now I want it to always print a leading zero if myNum only requires one digit:

unsigned char myNum = 0x8;
// Pretend std::hex takes an argument to specify number of digits.
clog << "Output: " << std::hex(2) << int(myNum) << endl;
// Desired:
//   Output: 08

So how can I actually do this?

like image 931
WilliamKF Avatar asked Feb 27 '11 02:02

WilliamKF


People also ask

How do you add leading zeros to a number in C?

Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4. val = N. ToString("0000");

How do I add a 0 in front of a number in C++?

Using std::format Starting with C++20, we can use the formatting library to add leading zeros to the string. It provides the std::format function in the header <format> . With C++17 and before, we can use the {fmt} library to achieve the same.

How do you find leading zeros?

A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, James Bond's famous identifier, 007, has two leading zeros.

Can an int have leading zeros?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.


2 Answers

It's not as clean as I'd like, but you can change the "fill" character to a '0' to do the job:

your_stream << std::setw(2) << std::hex << std::setfill('0') << x;

Note, however, that the character you set for the fill is "sticky", so it'll stay '0' after doing this until you restore it to a space with something like your_stream << std::setfill(' ');.

like image 198
Jerry Coffin Avatar answered Sep 23 '22 06:09

Jerry Coffin


This works:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int x = 0x23;
  cout << "output: " << setfill('0') << setw(3) << hex << x << endl;
}

output: 023

like image 39
jterrace Avatar answered Sep 21 '22 06:09

jterrace