avr39ripe

cppFileIOBasicProducts

Jun 16th, 2021
795
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. struct Product
  5. {
  6.     int id;
  7.     char name[15];
  8.     int count;
  9.  
  10.     void print()
  11.     {
  12.         std::cout << id << ' ' << name << ' ' << count << '\n';
  13.     }
  14. };
  15.  
  16. void printProduct(const Product& product)
  17. {
  18.     std::cout << product.id << ' ' << product.name << ' ' << product.count << '\n';
  19. }
  20.  
  21. void listProducts(Product* begin, Product* end)
  22. {
  23.     for (auto product{ begin }; product != end; ++product)
  24.     {
  25.         product->print();
  26.     }
  27. }
  28.  
  29. void listProducts(Product* products, int productsSize)
  30. {
  31.     for (int i{ 0 }; i < productsSize; ++i)
  32.     {
  33.         products[i].print();
  34.         //printProduct(products[i]);
  35.     }
  36. }
  37.  
  38. void saveProducts(Product* begin, Product* end)
  39. {
  40.     std::ofstream outf;
  41.     outf.open("products.txt");
  42.     for (auto product{ begin }; product != end; ++product)
  43.     {
  44.         outf << product->id << '\n';
  45.         outf << product->name << '\n';
  46.         outf << product->count << '\n';
  47.     }
  48.     outf.close();
  49. }
  50.  
  51. void loadProducts(Product* begin, Product* end)
  52. {
  53.     std::ifstream inf;
  54.     inf.open("products.txt");
  55.     for (auto product{ begin }; product != end; ++product)
  56.     {
  57.         inf >> product->id;
  58.  
  59.         inf.ignore(100, '\n');
  60.         inf.getline(product->name, 15);
  61.  
  62.         inf >> product->count;
  63.     }
  64.     inf.close();
  65. }
  66.  
  67. int main()
  68. {
  69.     const int productsSize{ 3 };
  70.     Product products[productsSize]{
  71.         {1,"apple",12},
  72.         {2,"orange",24},
  73.         {3,"lemon",42}
  74.     };
  75.  
  76.     auto productsEnd{ products + productsSize };
  77.  
  78.     std::cout << "Original Products:\n";
  79.     listProducts(products, productsEnd);
  80.     //listProducts(products, productsSize);
  81.     std::cout << '\n';
  82.  
  83.     saveProducts(products, productsEnd);
  84.  
  85.     Product fileProducts[productsSize];
  86.     auto fileProductsEnd{ fileProducts + productsSize };
  87.  
  88.     loadProducts(fileProducts, fileProductsEnd);
  89.  
  90.     std::cout << "Loaded Products:\n";
  91.     listProducts(fileProducts, fileProductsEnd);
  92.     std::cout << '\n';
  93.    
  94.     std::cout << std::boolalpha << (products[0].id == fileProducts[0].id) << '\n' <<
  95.         (strcmp(products[0].name, fileProducts[0].name) == 0) << '\n' <<
  96.         (products[0].count == fileProducts[0].count) << '\n';
  97. }
RAW Paste Data