Answer to Question #330815 in C++ for Harsh

Question #330815

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

1
Expert's answer
2022-04-19T08:50:48-0400
#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;
		}
	}
}





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS