Skip to content
rdavidPublic

About

C++ template that prints string and numeric data as an aligned, sortable table

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

Pretty Table

About

This C++ template prints string and numeric data as an aligned, sortable table. It calculates column widths after all fields are known. The template requires only the standard library. Copy PrettyTable.h and AlphaNum.h into a project to use it. The project also has a website. Column sorting uses Dirk Jagdmann’s implementation of the alphanum algorithm for human-friendly ordering. The following snippet shows typical usage:

CPrettyTable<int, const char*, double> tbl("num", "name", "score");
for (int i = 0; i < 5; ++i) {
  tbl.Add(i + 1, "FooBar", 2.5 * (i + 1));
}
tbl.SetCaption("FooBar");
tbl.Dump(std::cerr);

The snippet prints the following output to the standard error stream:

+-----+[ FooBar ]------+
| num | name   | score |
+-----+--------+-------+
|   1 | FooBar |   2.5 |
|   2 | FooBar |     5 |
|   3 | FooBar |   7.5 |
|   4 | FooBar |    10 |
|   5 | FooBar |  12.5 |
+-----+--------+-------+

API

Each template parameter sets the type of one column, up to 20 columns. A column accepts any type that supports operator<<. Numeric columns align right and other columns align left.

Method Description

CPrettyTable()

Creates a table without a header row.

Add(v1, …​)

Appends a row with one value per column. Omitted trailing values leave their cells empty.

SetCaption(s)

Embeds a caption into the top border. A NULL caption removes it. A long caption widens the columns to fit.

Sort(col, order)

Sorts data rows by the zero-based column with the alphanum algorithm. The order is ePTSO_Ascending by default or ePTSO_Descending. The header row stays on top.

Dump(out)

Prints the table to an output stream. Each line, including the first one, starts with a newline.

Get()

Returns the printed table as a string.

Size()

Returns the number of data rows without the header row.

IsEmpty()

Reports whether the table has no data rows.

Clear()

Removes all data rows and keeps the header row.

Build

The project uses Daniel J. Bernstein’s build system, redo. You can install Sergey Matveev’s goredo implementation.

Test

redo test builds the debug application and compares its output with the recorded golden file. redo lint applies the following linters to the source files: actionlint, checkmake, reuse, shellcheck, shfmt, typos, yamllint, zizmor.

License

ptable is copyrighted by David Rabkin and available under the Zero-Clause BSD license.

About

C++ template that prints string and numeric data as an aligned, sortable table

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages