Show zeros to the left of an integer in C ++

7

Hi, I have a 4-digit integer, which sometimes for example, will be vetted, sometimes it will have zeros to its left, but the problem is that I do not know how to show the leading zeros. Let's suppose that I have the following integer:

0382

How could I do to show it with a cout or a printf the zeros on its left since my number for example will be four characters. Or sometimes it will have more zero as I can show the zeros on the left. In my attempt I'll make a cout:

int i;
i=0382;
cout << i;

But will he show it to me as 382 as I could do to show these zeros?

    
asked by Sergio Ramos 11.03.2017 в 19:03
source

3 answers

3

You can use cout.fill and cout.width .

#include <iostream>
using namespace std;

int main() {
    // your code goes here

    int i;
    i = 382;

    cout.fill  ('0');    
    cout.width ( 4 );
    cout << i;

    return 0;
}

ideoneTest

    
answered by 11.03.2017 / 20:03
source
3

Includes the iomanip library

int i = 382;
std::cout << std::setfill('0') << std::setw(4) << i;

Putting 0 in an integer is useless because they are ignored ... Zeros are added when printing the value

    
answered by 11.03.2017 в 19:37
3

You can use printf instead of cout .

#include <iostream>
using namespace std;

int main()
{
   int i;
   i = 382;
   printf("%04d\n", i);
   return 0;
}
    
answered by 12.03.2017 в 04:58