-
Notifications
You must be signed in to change notification settings - Fork 10
/
TablePrinter.h
114 lines (90 loc) · 2.53 KB
/
TablePrinter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#ifndef __TablePrinter__
#define __TablePrinter__
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <cmath>
#include "util.h"
namespace bprinter {
class endl{};
class greyon{};
class greyoff{};
/** \class TablePrinter
Print a pretty table into your output of choice.
Usage:
TablePrinter tp(&std::cout);
tp.AddColumn("Name", 25);
tp.AddColumn("Age", 3);
tp.AddColumn("Position", 30);
tp.PrintHeader();
tp << "Dat Chu" << 25 << "Research Assistant";
tp << "John Doe" << 26 << "Professional Anonymity";
tp << "Jane Doe" << tp.SkipToNextLine();
tp << "Tom Doe" << 7 << "Student";
tp.PrintFooter();
\todo Add support for padding in each table cell
*/
class TablePrinter{
public:
TablePrinter(std::ostream * output, const std::string & separator = "|");
~TablePrinter();
int get_num_columns() const;
int get_table_width() const;
void set_separator(const std::string & separator);
void set_flush_left();
void set_flush_right();
void AddColumn(const std::string & header_name, int column_width);
void PrintHeader();
void PrintFooter();
TablePrinter& operator<<(UNUSED endl input){
while (j_ != 0){
*this << "";
}
return *this;
}
// Can we merge these?
TablePrinter& operator<<(float input);
TablePrinter& operator<<(double input);
TablePrinter& operator<<(UNUSED greyon input);
TablePrinter& operator<<(UNUSED greyoff input);
template<typename T> TablePrinter& operator<<(T input){
if (j_ == 0)
*out_stream_ << "|";
if(flush_left_)
*out_stream_ << std::left;
else
*out_stream_ << std::right;
std::stringstream string_out;
string_out << input;
// Leave 3 extra space: One for negative sign, one for zero, one for decimal
*out_stream_ << " "
<< std::setw(column_widths_.at(j_) - 2)
<< string_out.str().substr(0, column_widths_.at(j_) - 2)
<< " ";
if (j_ == get_num_columns()-1){
*out_stream_ << "|\n";
i_ = i_ + 1;
j_ = 0;
} else {
*out_stream_ << separator_;
j_ = j_ + 1;
}
return *this;
}
private:
void PrintHorizontalLine();
template<typename T> void OutputDecimalNumber(T input);
std::ostream * out_stream_;
std::vector<std::string> column_headers_;
std::vector<int> column_widths_;
std::string separator_;
int i_; // index of current row
int j_; // index of current column
int table_width_;
bool flush_left_;
};
}
#include "TablePrinter.tpp.h"
#endif