C++: formatting with cout function

PookyBoy

Senior member
Aug 18, 2001
200
0
0
if I did this:
int i=1
printf("%03d\n", i);
then it would print: "001"

How can I do this with the cout fucntion?
I'm need to print some stuff to a file and so i'm using the ostream class. When outputting to the file you use << like regular cout function so that's why I want to know this.
Thanks.
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
Try
cout << setf('0') << setw(3) << i << endl;

You must include iomanip. Also the setf() function is permanent while the setw() is only active for the next field.
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Another way would be to use sprintf instead of printf.

Create a character array buffer for the sprintf and then do the cout << buffer
 

PCHPlayer

Golden Member
Oct 9, 2001
1,053
0
0
Yes you could use sprintf or snprintf, but the << operator is a better way to go in general. Personally I don't use char buffers unless I have to interface with legacy C routines. I never worry about how big to make a buffer or if some routine like sprintf will overflow the buffer and cause an error 10,000 lines of execution later. I guess I'm just a C++ purist.