Skip to content

Instantly share code, notes, and snippets.

@DrFrankenstein
Last active November 25, 2016 18:19
Show Gist options
  • Save DrFrankenstein/3a34fdc551ddbaa7c3887e79879736f6 to your computer and use it in GitHub Desktop.
Save DrFrankenstein/3a34fdc551ddbaa7c3887e79879736f6 to your computer and use it in GitHub Desktop.
Formatting with iostreams
#include <iostream>
#include <string>
#include <array>
#include <iomanip>
#include <numeric>
using namespace std;
struct Item
{
unsigned sku;
string name;
unsigned qty;
double price;
double total() const { return this->qty * this->price; }
};
array<Item, 6> items = {{
{271016086, "Pencil", 10, .8},
{500598995, "Eraser", 3, 2.},
{926084379, "Calculator", 1, 11.99},
{707202821, "Laptop Computer", 1, 1416.75},
{55492254, "Laptop Bag", 1, 150.},
{4447, "$25 Discount", 3, -25.}
}};
int main()
{
cout << "SKU Item Qty Price Total\n"
"---------------------------------------------------" << endl;
for (Item item : items)
{
// SKU
cout << setw(10) << right << setfill('0') << item.sku << ' ';
// Name
cout << setw(20) << left << setfill(' ') << item.name << ' ';
// Qty
cout << setw(3) << right << item.qty << ' ';
// Price
cout << setw(7) << internal << setprecision(2) << fixed << item.price << ' ';
// Total
cout << setw(7) << item.total() << endl;
}
double total = accumulate(begin(items), end(items), 0.,
[](double total, Item item) { return total + item.total(); });
cout << "TOTAL: " << setw(44) << setfill('.') << right << total << endl;
}
SKU Item Qty Price Total
---------------------------------------------------
0271016086 Pencil 10 0.80 8.00
0500598995 Eraser 3 2.00 6.00
0926084379 Calculator 1 11.99 11.99
0707202821 Laptop Computer 1 1416.75 1416.75
0055492254 Laptop Bag 1 150.00 150.00
0000004447 $25 Discount 3 - 25.00 - 75.00
TOTAL: .....................................1517.74
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment