Write two programs in c++ which will work with a structure. The first program wi
ID: 674855 • Letter: W
Question
Write two programs in c++ which will work with a structure.
The first program will use a structure to store the following inventory data in a file: Item Description Quantity on Hand Wholesale Cost Retail Cost Date Added to Inventory The program will write five records to an output file for different items; the quantity, costs, and date for each item will be different from the other items.
The second program will read the file created by the first program using the same structure. The second program will calculate and display the following information: total wholesale value of the inventory total retail value of the inventory total quantity of all items in the inventory
Explanation / Answer
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int DES = 20;
//declare variables
void Add();
void Display();
void Edit();
struct SInventory
{
char item[DES];
int qty;
int wcost;
int rcost;
char date[10];
};
//Main function
int main()
{
int choice;
do
{
cout << "MENU" << endl;
cout << "1. Add Record: " << endl;
cout << "2. Display Records: " << endl;
cout << "Please enter your selection." << endl;
cin >> choice;
switch (choice)
{
case 1:
Add();
break; //Add record
case 2:
Display();
break; //Display record
default: cout << "Invalid Selection" << endl;
}
} while
(choice <= 2);
system("PAUSE");
return 0;
}
void Add()
{
fstream fout;
const int size = 3;
char ch;
int i = 0;
fout.open("Records.txt", ios::cout);
SInventory inv;
//get data
do
{
cout << "Enter item description: " << endl;
cin.ignore();
cin.getline(inv.item, DES);
cout << "Enter quantity: " << endl;
cin >> inv.qty;
cout << "Enter wholesale cost: " << endl;
cin >> inv.wcost;
cout << "Enter retail cost: " << endl;
cin >> inv.rcost;
cout << "Enter date: " << endl;
cin.ignore();
cin.getline(inv.date, 10);
fout.write(reinterpret_cast<char*>(&inv), sizeof(inv));
cout << "Do you want to add another record? " << endl;
cin >> ch;
} while
(ch == 'Y' && 1 < 3);
fout.close();
}
void Display()
{
fstream fout;
fout.open("Records.txt", ios::in);
SInventory inv;
fout.read(reinterpret_cast <char*> (&inv), sizeof(inv));
while (!fout.eof())
{
cout << " Description : ";
cout << inv.item;
cout << " Quantity : ";
cout << inv.qty;
cout << " Wholesale Cost : ";
cout << inv.wcost;
cout << " Retail Cost : ";
cout << inv.rcost;
cout << " Date : ";
cout << inv.date;
fout.read(reinterpret_cast <char*> (&inv), sizeof(inv));
}
//close the file
fout.close();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.