Learn C++ · lesson 9 of 61 · about 8 minutes
Project: Character Sheet
Line up the hero's stats in neat columns and print a merchant's bill to two decimal places with <iomanip>.
What you'll learn
- Align columns with std::setw
- Print money with std::fixed and std::setprecision
- Combine strings, numbers and input
A character sheet
Games show stats in neat columns: names on the left, numbers lined up on the right. Spaces typed by hand break as soon as a number gets longer, so let the program pad them. From <iomanip>:
std::setw(8)makes the next value at least 8 characters widestd::leftandstd::rightchoose which side the padding goesstd::fixed << std::setprecision(2)prints doubles with exactly 2 decimal places
Stats in two columns
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::left << std::setw(8) << "Health" << std::right << std::setw(5) << 85 << "\n";
std::cout << std::left << std::setw(8) << "Gold" << std::right << std::setw(5) << 5 << "\n";
std::cout << std::left << std::setw(8) << "Speed" << std::right << std::setw(5) << 1.5 << "\n";
}Output
Health 85
Gold 5
Speed 1.5The merchant's bill
A merchant sells the hero two things. The bill reads each item and its price, then lines them up with a total, always with two decimal places.
Read two items, print an aligned bill
#include <iostream>
#include <string>
#include <iomanip>
int main() {
std::string first;
std::string second;
double firstPrice;
double secondPrice;
std::cin >> first >> firstPrice >> second >> secondPrice;
std::cout << std::fixed << std::setprecision(2);
std::cout << std::left << std::setw(10) << first << std::right << std::setw(8) << firstPrice << "\n";
std::cout << std::left << std::setw(10) << second << std::right << std::setw(8) << secondPrice << "\n";
std::cout << std::left << std::setw(10) << "Total" << std::right << std::setw(8) << firstPrice + secondPrice << "\n";
}Output
Potion 12.50
Map 7.25
Total 19.75Tip
setw only affects the very next value, so it's repeated for each column. fixed and setprecision stay on until you change them.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.