Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Permanent" std::setw

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.

like image 493
Miro Kropacek Avatar asked Jan 01 '09 15:01

Miro Kropacek


People also ask

What is std :: SETW?

The C++ function std::setw behaves as if member width were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams). It is used to sets the field width to be used on output operations.

What is the default output for SETW in C++?

The specialty of the setw C++ function is that it does not truncate the string if the width of the field is less. Instead, it sets the default value to 0 and displays the entire c++ string.


1 Answers

Well, it's not possible. No way to make it call .width each time again. But you can use boost, of course:

#include <boost/function_output_iterator.hpp> #include <boost/lambda/lambda.hpp> #include <algorithm> #include <iostream> #include <iomanip>  int main() {     using namespace boost::lambda;     int a[] = { 1, 2, 3, 4 };     std::copy(a, a + 4,          boost::make_function_output_iterator(                var(std::cout) << std::setw(3) << _1)         ); } 

It does create its own functor, but it happens behind the scene :)

like image 80
Johannes Schaub - litb Avatar answered Sep 18 '22 13:09

Johannes Schaub - litb