Repository navigation
Expand file tree
/
Copy pathInventory.cpp
More file actions
89 lines (74 loc) · 1.78 KB
/
Copy pathInventory.cpp
File metadata and controls
89 lines (74 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <fstream>
using namespace std;
class Inventory {
private:
string name;
int id;
float price;
int quantity;
public:
void accept() {
cout << "Enter Item Name: ";
getline(cin, name);
cout << "Enter Item ID: ";
cin >> id;
cout << "Enter Price: ";
cin >> price;
cout << "Enter Quantity: ";
cin >> quantity;
cin.ignore();
}
void display() {
cout << "\nItem Name: " << name;
cout << "\nItem ID: " << id;
cout << "\nPrice: " << price;
cout << "\nQuantity: " << quantity << endl;
}
void writeToFile(ofstream &fout) {
fout << name << endl;
fout << id << endl;
fout << price << endl;
fout << quantity << endl;
}
void readFromFile(ifstream &fin) {
getline(fin, name);
fin >> id;
fin >> price;
fin >> quantity;
fin.ignore();
}
};
int main() {
int n;
cout << "Enter number of items: ";
cin >> n;
cin.ignore();
Inventory items[n];
for (int i = 0; i < n; i++) {
cout << "\n--- Item " << i + 1 << " ---\n";
items[i].accept();
}
ofstream fout("inventory.txt");
if (!fout) {
cout << "Error opening file (writing mode)!" << endl;
return 1;
}
for (int i = 0; i < n; i++) {
items[i].writeToFile(fout);
}
fout.close();
cout << "\nRecords written successfully!!!\n";
ifstream fin("inventory.txt");
if (!fin) {
cout << "Error opening file (reading mode)!" << endl;
return 1;
}
cout << "\nRecords from file.....\n";
for (int i = 0; i < n; i++) {
items[i].readFromFile(fin);
items[i].display();
}
fin.close();
return 0;
}