Create 5 objects of class Product, input its product code, name and quantity and write into the
FILE. Later, display the data of all objects by reading from the FILE
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Product
{
int code;
string name;
int quantity;
public:
Product(int _code, string _name, int _quantity)
:code(_code), name(_name), quantity(_quantity){}
int GetCode() { return code; }
string GetName() { return name; }
int GetQuant() { return quantity; }
};
int main()
{
const int N = 5;
Product arr[N] = { Product(123,"Apple",30),
Product(125,"Lemon",25),Product(128,"Meal",20),
Product(123,"Fish",50),Product(113,"Cherry",25)};
ofstream of;
of.open("Products.txt");
if (!of.is_open())
cout << "File isn`t opened!";
else
{
for (int i = 0; i < N; i++)
{
of << arr[i].GetCode() << " " << arr[i].GetName() << " "
<< arr[i].GetQuant() << endl;
}
}
of.close();
ifstream ifs("Products.txt");
if (!ifs.is_open())
cout << "File isn`t opened!";
else
{
string line;
while (getline(ifs, line, '\n'))
{
cout << line << endl;
}
}
}
Comments
Leave a comment