有什么方法可以永久设置std::setw
机械手(或其功能)吗?width
看这个:
#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;
}
运行后,我看到:
001 2 4 8 10 20 40 80 100
001 002 004 008 010 020 040 080 100
即除了必须为每个条目设置的setw
/之外,每个操纵器都占有一席之地。width
是否有任何优雅的方式如何使用std::copy
(或其他)setw
?我所说的优雅当然不是指创建自己的仿函数或函数来将内容写入std::cout
.