C/C++ Arena

Step 2 of 6

Formatting tables with iomanip

Printing numbers in neat columns needs control over width, alignment and decimal places. In C that's printf("%-10s%6.2f"). In C++ it's the manipulators from <iomanip>:

Manipulator Effect
std::setw(n) pad the next item to width n (only the next one!)
std::left, std::right alignment inside that width (sticky)
std::fixed + std::setprecision(2) always 2 digits after the decimal point (sticky)
std::setfill('0') pad with a character other than space (sticky)

"Sticky" settings stay on the stream until you change them. setw resets after each item.

#include <iomanip>
#include <iostream>

int main() {
    std::cout << std::fixed << std::setprecision(2);
    std::cout << std::left << std::setw(8) << "item" << std::right << std::setw(8) << "price" << "\n";
    std::cout << std::left << std::setw(8) << "tea" << std::right << std::setw(8) << 3.5 << "\n";
    std::cout << std::left << std::setw(8) << "cake" << std::right << std::setw(8) << 12.999 << "\n";
    std::cout << std::setfill('0') << std::setw(2) << 7 << ":" << std::setw(2) << 5 << "\n";
}
item       price
tea         3.50
cake       13.00
07:05

Reading the example

The K/D detail in your task

kills / deaths with two ints does integer division. Convert one side first: static_cast<double>(kills) / d. And handle the "0 deaths counts as 1" rule before dividing.

Your turn: read name kills deaths rows and print a table: name left-aligned in 10 columns, kills and deaths right-aligned in 4 columns each, then the K/D ratio right-aligned in 6 columns with 2 decimals (use 0 deaths as 1 death).

Previous: Parsing with istringstream Next: Building strings with ostringstream