Save struct to a file and read struct from a file - C++ Data Type

C++ examples for Data Type:struct

Description

Save struct to a file and read struct from a file

Demo Code

#include <iostream>
using namespace std;
#include <stdlib.h>
#include <iomanip>
#include <stdio.h>
struct inventory            // Global structure definition.
{
   long int storage;
   int access_time;
   char vendor_code;
   float cost;//from   w  ww.  j  a  v  a2 s.c  om
   float price;
};              // No structure variables defined globally.
void disp_menu(void);
struct inventory enter_data();
void see_data(inventory disk[125], int num_items);
void main()
{
   inventory disk[125]; 
   int ans;
   int num_items=0;            

   do
   {
      do
      {
         disp_menu(); 
         cin >> ans;               // Get user's request.
      } while ((ans<1) || (ans>3));
      switch (ans)
      {
         case (1): {
            disk[num_items] = enter_data(); // Enter disk data.
            num_items++;   // Increment number of items.
            break;
         }
         case (2): {
            see_data(disk, num_items);  // Display disk data.
            break;
         }
         default : {
            break;
         }
      }
   }  while (ans!=3);           // Quit program when user is done.
   return;
}
void disp_menu(void)
{
   cout << "Do you want to:\n\n";
   cout << "\t1. Enter new item in inventory\n\n";
   cout << "\t2. See inventory data\n\n";
   cout << "\t3. Exit the program\n\n";
   cout << "What is your choice? ";
   return;
}
inventory enter_data()
{
   inventory disk_item;   // Local variable to fill with input.
   cout << "\n\nWhat is the next drive's storage in bytes? ";
   cin >> disk_item.storage;
   cout << "What is the drive's access time in ms? ";
   cin >> disk_item.access_time;
   cout << "What is the drive's vendor code (A, B, C, or D)? ";
   fflush(stdin);  // Discard input buffer before accepting character.
   disk_item.vendor_code = getchar();
   getchar();  // Discard carriage return
   cout << "What is the drive's cost? ";
   cin >> disk_item.cost;
   cout << "What is the drive's price? ";
   cin >> disk_item.price;
   return (disk_item);
}
void see_data(inventory disk[125], int num_items)
{
   int ctr;
   cout << "\n\nHere is the inventory listing:\n\n";
   for (ctr=0;ctr<num_items;ctr++)
   {
      cout << "Storage: " << disk[ctr].storage << "\t";
      cout << "Access time: " << disk[ctr].access_time << "\n";
      cout << "Vendor code: " << disk[ctr].vendor_code << "\t";
      cout << setprecision(2);
      cout << "Cost: $" << disk[ctr].cost << "\t";
      cout << "Price: $" << disk[ctr].price << "\n";
   }
   return;
}

Result


Related Tutorials