suppose an electronic store sell ten types of mobile phone. each phone has its own model number, screen size, RAM size and price. Write a program to create a file named "mobile.txt" that store information for ten mobile phones and display all the information.
Here's an example program that reads information for ten mobile phones from the user and stores it in a file named "mobile.txt", and then reads the information from the file and displays it:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Mobile {
string model;
float screenSize;
int ram;
float price;
};
void writeToFile(Mobile phones[], int size) {
ofstream file("mobile.txt");
if (file.is_open()) {
for (int i = 0; i < size; i++) {
file << phones[i].model << " ";
file << phones[i].screenSize << " ";
file << phones[i].ram << " ";
file << phones[i].price << endl;
}
file.close();
cout << "Data written to file successfully." << endl;
} else {
cout << "Failed to open file." << endl;
}
}
void readFromFile() {
ifstream file("mobile.txt");
if (file.is_open()) {
Mobile phone;
while (file >> phone.model >> phone.screenSize >> phone.ram >> phone.price) {
cout << "Model: " << phone.model << endl;
cout << "Screen size: " << phone.screenSize << endl;
cout << "RAM: " << phone.ram << endl;
cout << "Price: " << phone.price << endl;
cout << endl;
}
file.close();
} else {
cout << "Failed to open file." << endl;
}
}
int main() {
Mobile phones[10];
cout << "Enter details for 10 mobile phones:" << endl;
for (int i = 0; i < 10; i++) {
cout << "Mobile " << i+1 << endl;
cout << "Model: ";
getline(cin, phones[i].model);
cout << "Screen size: ";
cin >> phones[i].screenSize;
cout << "RAM: ";
cin >> phones[i].ram;
cout << "Price: ";
cin >> phones[i].price;
cin.ignore();
cout << endl;
}
writeToFile(phones, 10);
cout<< "Reading data from file..." << endl;
readFromFile();
return 0;
}
Comments
Post a Comment
If you have any doubts, please let me know