Question 2
Back to Exercise
Print an invoice with left-aligned item names, right-aligned quantity, price and amount (two decimals), a dashed separator line and a grand total.
Solution
#include <iomanip>
#include <iostream>
#include <string>
int main() {
struct Line { std::string item; int qty; double price; };
Line lines[] = {{"Keyboard", 1, 1249.0}, {"USB cable", 3, 199.5}, {"Mouse pad", 2, 149.0}};
std::cout << std::left << std::setw(12) << "Item" << std::right << std::setw(5) << "Qty"
<< std::setw(10) << "Price" << std::setw(11) << "Amount" << '\n'
<< std::setfill('-') << std::setw(38) << "" << std::setfill(' ') << '\n'
<< std::fixed << std::setprecision(2);
double total = 0;
for (const auto& l : lines) {
double amount = l.qty * l.price;
total += amount;
std::cout << std::left << std::setw(12) << l.item << std::right << std::setw(5) << l.qty
<< std::setw(10) << l.price << std::setw(11) << amount << '\n';
}
std::cout << std::left << std::setw(27) << "Total" << std::right << std::setw(11) << total << '\n';
return 0;
}
Item Qty Price Amount -------------------------------------- Keyboard 1 1249.00 1249.00 USB cable 3 199.50 598.50 Mouse pad 2 149.00 298.00 Total 2145.50
setw must be repeated for every field, while left/right, fill and precision persist. Printing an empty string with a width and a fill character draws the separator line.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!