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. 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:

main.cpp — CPrettyTable demo
$ g++ -std=c++03 -o app main.cpp && ./app
1 +-----+[ FooBar ]------+
2 | num | name | score |
+-----+--------+-------+
3 | 1 | FooBar | 2.5 |
| 2 | FooBar | 5 |
| 3 | FooBar | 7.5 |
| 4 | FooBar | 10 |
| 5 | FooBar | 12.5 |
4 +-----+--------+-------+

What the numbers point at

  1. 1

    SetCaption embeds its text into the first delimiter line instead of printing a separate title row.

  2. 2

    Column titles come straight from the constructor arguments — there's no separate header-setting call.

  3. 3

    Numeric types report is_specialized=true, so CPrettyTable right-aligns them automatically. Strings stay left-aligned.

  4. 4

    Column widths are fixed only after every row is known, so a five-character caption or a six-character name both fit without truncation.

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.