While it is typical to put a class in a separate file from the main function fil
ID: 3539852 • Letter: W
Question
While it is typical to put a class in a separate file from the main function file, for this program, put the class and main in the same file.
Write a class that describes an inventory item. An item has the following data members %u2013 all private:
int id
int quantity
float price
string name
An item also has public methods:
void setItem(); //sets all four item attributes
void printItem(); //prints all four attributes of an item
void updateQuantity(int); //adds the integer argument to the quantity
The items are read from the file "items.dat", and the read is to end of file. The main program can handle up to 1000 inventory items. After the inventory is read in, main should loop through all the items asking how much the quantity should be changed by. Then the program will print out the new inventory. For example if items.dat contained:
13254 25 57.32 widgeta
23344 10 3.45 widgetb
35655 52 4.10 widgetc
A run of the program might be:
What is the change in the quantity for widgeta? 10
What is the change in the quantity for widgetb? -5
What is the change in the quantity for widgetc? -32
The new inventory:
13254 35 57.32 widgeta
23344 5 3.45 widgetb
35655 20 4.10 widgetc
Explanation / Answer
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
class inventory_item
{
public:int id;
public:int quantity;
public:float price;
public:string name;
public:void setItem(int id,int quantity,float price,string name)
{
this->id=id;
this->quantity=quantity;
this->price=price;
this->name=name;
}
public:void printItem()
{
cout<<id<<" "<<quantity<<" "<<price<<" "<<name<<endl;
}
public:void updateQuantity(int qty)
{
quantity=quantity+qty;
}
};
int main()
{
inventory_item item[1000];
int index =0;
string line;
char * pnt;
char * tokenpar;
int id;
int quantity;
float price;
string name;
int change;
ifstream myfile ("items.dat");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
tokenpar=strdup(line.c_str());
pnt=strtok( tokenpar, "," );
id=atoi(pnt);
pnt = strtok( NULL, "," );
quantity=atoi(pnt);
pnt = strtok( NULL, "," );
price=atof(pnt);
pnt = strtok( NULL, "," );
name=pnt;
item[index].setItem(id,quantity,price,name);
index++;
}
for(int i=0;i<=index;i++)
{
cout<<"What is the change in the quantity for "<<item[index].name<<endl;
cin>>change;
item[i].updateQuantity(change);
}
for(int i=0;i<=index;i++)
{
item[i].printItem();
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
------------------------------------------------------------------
Please ensure the file has data in below format:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.