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
std::fixed << std::setprecision(2)is set once at the top and applies to every floating point number after it. Withoutstd::fixed,setprecision(2)would mean "2 significant digits" and print3.5as3.5and12.999as13.std::setw(8)is written before every item that needs padding, because it only lasts for one item.std::leftandstd::rightare sticky, so a table that mixes alignments has to switch back and forth, as each row does here.12.999rounds to13.00:setprecisionrounds, it never just chops digits off.- If a value is wider than the
setw, it's printed in full; the column just gets pushed over. Nothing is ever cut off.
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