Print leading zeros with C++ output operator


Here we will see how to print leading zeros as output in C++. We know that if we directly put some zeros before some numeric values, then all zeros are discarded, and only exact numbers are printed.

In C, we can solve this problem by using some options of format specifier. In C++ we can manipulate the output sequence using iomanip library. In this library we will get setw() function to make some space between previous text and current text. Then we can use setfill(char) function to add some characters into that field.

Please check the following code to get the idea about setw() and setfill().

Example Code

#include<iostream>
#include<iomanip>
using namespace std;
int main() {
   int number = 256; //want to print 00000256, so total 8
   characters
   cout << setw(8) << setfill('0') << number;
}

Output

00000256

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements