I’m trying to write a simple C++ program to do some iterative and tedious math. It’s coming along well, and now I’m to the point where I’m getting fussy about formatting.
The problem is, I want a number to be output with its sign ahead of a number in a fixed length field, filled with leading zeros where necessary. I may want to use a different character later, so I’m trying to make the setfill IO manipulator work for me.
My problem is that I can’t get the sign to stay before the field. If I have an integer like -1246, I want it do display as -00001246. And I want 21597 to display as +00021597. But in the above code, the answer displays as 000-1246
Is there any way to do this simply with io flags? I don’t want to have to make some sort of stupid condtional statement just to format my numbers this way.
I agree with np_complete. The following works in my compiler, and I think it’s ANSI, but it looks like you have some things that I don’t, like “setfill”.
The setfill( ) function inserted into an output stream via cout has the same effect as executing the cout.fill( ) function separately. The following code will have the same output as Achernar’s (ignoring the fact that answer has no value set to it):
Aha I see what I was doing wrong. I just needed to include iomanip, something I’d never heard of. Ugh, I’ve been doing it the long way all these years!