Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- struct Product
- {
- int id;
- char name[15];
- int count;
- void print()
- {
- std::cout << id << ' ' << name << ' ' << count << '\n';
- }
- };
- void printProduct(const Product& product)
- {
- std::cout << product.id << ' ' << product.name << ' ' << product.count << '\n';
- }
- void listProducts(Product* begin, Product* end)
- {
- for (auto product{ begin }; product != end; ++product)
- {
- product->print();
- }
- }
- void listProducts(Product* products, int productsSize)
- {
- for (int i{ 0 }; i < productsSize; ++i)
- {
- products[i].print();
- //printProduct(products[i]);
- }
- }
- void saveProducts(Product* begin, Product* end)
- {
- std::ofstream outf;
- outf.open("products.txt");
- for (auto product{ begin }; product != end; ++product)
- {
- outf << product->id << '\n';
- outf << product->name << '\n';
- outf << product->count << '\n';
- }
- outf.close();
- }
- void loadProducts(Product* begin, Product* end)
- {
- std::ifstream inf;
- inf.open("products.txt");
- for (auto product{ begin }; product != end; ++product)
- {
- inf >> product->id;
- inf.ignore(100, '\n');
- inf.getline(product->name, 15);
- inf >> product->count;
- }
- inf.close();
- }
- int main()
- {
- const int productsSize{ 3 };
- Product products[productsSize]{
- {1,"apple",12},
- {2,"orange",24},
- {3,"lemon",42}
- };
- auto productsEnd{ products + productsSize };
- std::cout << "Original Products:\n";
- listProducts(products, productsEnd);
- //listProducts(products, productsSize);
- std::cout << '\n';
- saveProducts(products, productsEnd);
- Product fileProducts[productsSize];
- auto fileProductsEnd{ fileProducts + productsSize };
- loadProducts(fileProducts, fileProductsEnd);
- std::cout << "Loaded Products:\n";
- listProducts(fileProducts, fileProductsEnd);
- std::cout << '\n';
- std::cout << std::boolalpha << (products[0].id == fileProducts[0].id) << '\n' <<
- (strcmp(products[0].name, fileProducts[0].name) == 0) << '\n' <<
- (products[0].count == fileProducts[0].count) << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement