Can you use setfill() to set fill 2 digits?

463 Views Asked by At

Say if I want to display 2018 when the input is 18, how can I make it display the "20" in 2018? I tried using setfill("20") and it won't work as it's a string rather than a char. But when I used setfill('2'); it will display 2218.

1

There are 1 best solutions below

0
On

The formatting facility setfill() is designed to fill the empty space by repeating one single char. So it is not possible to obtain this effect, using a string.

For time formatting, you'd have the possibility to use put_time() with a formatting string to indicate the desired format (e.g. Y for 2018 and y for 18), provided you have a real date (so year 2018) passed in a tm structure.

In your case, you could try something like:

cout << (year<100 ? year:year+2000);   

But a better approach would be to either ensure that the date is entered on 4 digits (this will avoid you the future bug of the year 2100), or use some function for doing that, so that --if needed-- your future you could easily find the delicate places in your code.