Is there any way how to set std::setw
manipulator (or its function width
) permanently? Look at this:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
int main( void )
{
int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
std::cout.fill( '0' );
std::cout.flags( std::ios::hex );
std::cout.width( 3 );
std::copy( &array[0], &array[9], std::ostream_iterator<int>( std::cout, " " ) );
std::cout << std::endl;
for( int i = 0; i < 9; i++ )
{
std::cout.width( 3 );
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
After run, I see:
001 2 4 8 10 20 40 80 100
001 002 004 008 010 020 040 080 100
I.e. every manipulator holds its place except the setw
/width
which must be set for every entry. Is there any elegant way how to use std::copy
(or something else) along with setw
? And by elegant I certainly don't mean creating own functor or function for writing stuff into std::cout
.
Since
setw
andwidth
do not result in a persistent setting, one solution is to define a type that overridesoperator<<
, applyingsetw
before the value. This would allow anostream_iterator
for that type to function withstd::copy
as below.You could define: (1)
FixedWidthVal
as a template class with parameters for data type (typename
) and width (value), and (2) anoperator<<
for anostream
and aFixedWidthVal
that appliessetw
for each insertion.Then it could be applied with
std::copy
(or afor
loop):Output (demo)
Well, it's not possible. No way to make it call
.width
each time again. But you can use boost, of course:It does create its own functor, but it happens behind the scene :)