Specifying integer precision with Stream I/O

J

John Friedland

'printf' allows an integer to be printed with a precision.
"printf("|%5.2d|", 1)", for example, produces "| 01|".

This doesn't seem to be possible with stream I/O - 'precision' only
seems to be relevant to floating-point numbers. Can anyone tell me if
I can do the above with stream I/O?

I've attached a simple test program; the output is

| 01|
| 1|
|00001|

Thanks -

John

----------------------------------------
#include <stdio.h>
#include <iostream>
#include <iomanip>
int main(void) {
int a = 1;

printf("|%5.2d|\n", a);
std::cout
<< '|' << std::setw(5) << std::setprecision(2) << a
<< '|' << std::endl;
std::cout
<< '|' << std::setw(5) << std::setprecision(2)
<< std::setfill('0') << a << '|' << std::endl;
}
----------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top