1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
// I was able to read the text file and sort the list stated below using
// bubblesort but i don't know how to add up the total sum of the quantity
// acquired and sort the list in a decreasing alphabetical order without
// repeating the elements of each product with the same name? Thanks
// NAME CATEGORY QUANTITY
// walnuts 8 50
// pasta 3 7
// cheese 2 15
// bread 1 10
// salad 4 100
// pizza 5 15
// apples 6 16
// cherries 7 22
// bread 1 20
// cheese 2 5
// bread 6 20
// pasta 3 5
// bread 1 15
#include <fstream>
#include <iostream>
#include <limits>
#include <set>
#include <sstream>
#include <string>
class Item {
public:
Item(std::string name_arg, int category_arg, int quantity_arg);
bool operator<(const Item& other) const;
friend std::ostream& operator<<(std::ostream& os, const Item& rhs);
std::string name;
int category {},
quantity {};
};
Item::Item(std::string name_arg, int category_arg, int quantity_arg)
: name {name_arg}, category {category_arg}, quantity {quantity_arg}
{}
bool Item::operator<(const Item& other) const
{ return name < other.name; }
std::ostream& operator<<(std::ostream& os, const Item& rhs)
{
return (os << "Product name: " << rhs.name
<< "; category: " << rhs.category
<< "; available quantity: " << rhs.quantity << '\n');
}
std::set<Item>& loadFromFile(std::ifstream& source, std::set<Item>& catalog);
void waitForEnter();
int main()
{
std::string filename("products.txt");
std::ifstream infile(filename);
std::set<Item> products;
loadFromFile(infile, products);
for(const auto& p : products) { std::cout << p; }
waitForEnter();
return 0;
}
std::set<Item>& loadFromFile(std::ifstream& source, std::set<Item>& catalog)
{
std::string line;
while(std::getline(source, line)) {
std::stringstream tmpss(line);
int category {}, quantity {};
tmpss >> line >> category >> quantity;
Item tmp_item(line, category, quantity);
auto insertion = catalog.insert(tmp_item);
if(!insertion.second) {
tmp_item.quantity += (insertion.first)->quantity;
catalog.erase(insertion.first);
catalog.insert(tmp_item);
}
}
return catalog;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|