How we can make a nice table in C++ ? I always use "|" and "___" to manually create a a table, but it often messed up. Please give me some tutorial and if possible table's screenshot. Thank you as always^^.

Dani AI

Generated

For : three practical paths are common — formatted console output, a small helper to compute column widths, or a TUI/GUI widget. was right to point at stream manipulators; 's mention of curses is the usual next step when the table must be interactive. The core cause of the mess with manual | and ___ is variable cell widths (and UTF-8 / non‑monospaced fonts); computing column widths first avoids that.

A compact, reusable console approach: measure each column, then print rows with padding using std::setw and std::left/std::right. The example below shows how to build borders and print a vector of rows reliably.

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>

void print_table(const std::vector<std::vector<std::string>>& rows) {
    if (rows.empty()) return;
    size_t cols = 0;
    for (auto &r : rows) cols = std::max(cols, r.size());
    std::vector<size_t> w(cols, 0);
    for (auto &r : rows)
        for (size_t i = 0; i < r.size(); ++i)
            w[i] = std::max(w[i], r[i].size());

    auto border = [&]() {
        std::cout << '+';
        for (auto width : w) std::cout << std::string(width + 2, '-') << '+';
        std::cout << '\n';
    };

    border();
    for (auto &r : rows) {
        std::cout << '|';
        for (size_t i = 0; i < w.size(); ++i) {
            std::string cell = i < r.size() ? r[i] : "";
            std::cout << ' ' << std::left << std::setw(w[i]) << cell << ' ' << '|';
        }
        std::cout << '\n';
        border();
    }
}

For fewer lines of code and Python-like formatting, consider the {fmt} library (see its docs at https://fmt.dev/latest/index.html). For interactive terminal tables (keystrokes, windows, colors) use ncurses (intro: ). If Unicode is required, handle display width (not just byte length) — refer to wcwidth/character width helpers (see man page: https://man7.org/linux/man-pages/man3/wcwidth.3.html).

Recommended Answers

All 2 Replies

It takes some work. C++ ostream manipulators take practice getting used to. GUI custom controls are probably the easiest way to get things neat and tidy, but it takes a fair amount of knowledge in C/C++ to get comfortable using that type of code too.

A good reference book with examples of using the manipulators is the best resource I can think of to help you get it right.

you can try looking at the 'curses' library too...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.