Formater et aligner des données sur le flux de sortie standard n'est pas toujours quelque chose de très facile à réaliser. Cette classe est là pour palier à ce problème, grâce à elle, vous pouvez désormais afficher des données aussi alignées que dans un tableur
# include <iostream>
# include <iomanip>
# include <string>
# include <list>
# include <vector>
template < typename T>
class TableFormatter {
public :
TableFormatter (std:: basic_ostream< T> & os) : out_ (os) { }
~ TableFormatter ( ) { out_ < < flush;}
template < typename Cont>
void writeTableRow (const Cont& v, int width) {
ios_base:: fmtflags flags = out_.flags ( );
out_.flush ( );
out_ < < setprecision (2 ) < < fixed;
for (typename Cont:: const_iterator p = v.begin ( );
p ! = v.end ( ); + + p)
out_ < < setw (width) < < left < < * p;
out_ < < endl;
out_.setf (flags);
}
private :
std:: basic_ostream< T> & out_;
} ;
|
Et voici un exemple d'utilisation
int main ( ) {
TableFormatter< char > fmt (cout);
vector< string> vs;
vs.push_back ( " Sunday " );
vs.push_back ( " Monday " );
vs.push_back ( " Tuesday " );
vector< string> vs2;
vs2.push_back ( " John " );
vs2.push_back ( " Susie " );
vs2.push_back ( " Alan Smith " );
fmt.writeTableRow (vs, 12 );
fmt.writeTableRow (vs2, 12 );
list< double > vd;
vd.push_back (4 .0 );
vd.push_back (3 .0 );
vd.push_back (2 .0 );
fmt.writeTableRow (vd, 12 );
}
|
|