Re: ios output width
James Kanze wrote:
On Dec 6, 5:27 pm, Ralf Goertz
<r_goe...@expires-2006-11-30.arcornews.de> wrote:
I'd like to use copy() to send the content of an integer
container to cout. How can I make sure that /all/ of them are
printed with width 2?
You could write a class along the lines of:
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
int w = dest.width() ;
dest << obj.i ;
dest.width( w ) ;
return *dest ;
}
private:
int i ;
} ;
and invoke:
std::cout.width( 2 ) ;
copy( v.begin(), v.end(),
std::ostream_iterator< FixedWidthInt >( std::cout ) ) ;
That - to my surprise - didn't work. That is (after having changed
"return *dest" to "return dest") it compiled but only wrote the first
int with width 2 like my own attempt.
gcc-Version 4.2.1 (SUSE Linux)
I don't like it, though; it more or less changes the expected
behavior of the ostream. Alternatively, if the width is always
constant, you could use a template:
template< int w >
class FixedWidthInt
{
public:
FixedWidthInt( int i ) : i( i ) {}
friend std::ostream& operator<<(
std::ostream& dest,
FixedWidthInt const&obj )
{
dest << std::setw( w ) << obj.i ;
return *dest ;
}
private:
int i ;
} ;
I also like this better and it worked (again after replacing "*dest" by
"dest"). Something like that was what I expected to find in the standard.
This seems more acceptable to me, since you aren't counting on
the width not changing. (I.e. this FixedWidthInt doesn't cause
the width not to be reset, against expectations of a <<
operator. The preceding one does.)
Finally, you could arrange that FixedWidthInt get the width, not
from a template argument (which must be a compile time
constant), but from a special format field, set by
maniipulators. Something like the following:
I think I would go with the template as I usually know at compile time
what width I need.
I thought using format flags with setf would be the way to do
it like when I want to output the integers in say octal. But
there are no format "flags" for width. What can I do?
See above. The real solution is to design and implement an
ostream_iterator that is useful, but that's decidedly
non-trivial. Failing that, I suspect that the template version
of FixedWidth that I propose above might be a useful snippet.
Yes it is. Thanks a lot.
Ralf