LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Input/Output Programs · Question 2

Print an aligned invoice table with setw and setfill in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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
main.cpp
#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;
}

Output Verified by compiling and running

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links