c++
Create a program that saves data beyond the life time of the program.
Utilize the following struct:
struct PetRock { string name; int age; };
When the program runs, it first checks to see if a file contains data (PetRocks). If the file contains data then the data will be read from the file into an array of size 3 and will be printed (assume there will be no more than 3 objects saved in the data file). If no data is contained within the file, 3 PetRock objects will be created and written to the file.
Sample Output
First time executing the program
No data in file Collecting Pet Rocks... Storing Pet Rocks...
Second time executing the program
Data found in file Storing Pet Rocks into array... Pet Rocks: Name: Pete Age: 1032 Name: Eugene Age: 124832 Name: Dwayne the Rock Age: 2374
#include <iostream> #include <fstream> #include <string> using namespace std; struct PetRock { string name; int age; }; int main() { ifstream in("pet_rocks.txt"); PetRock data[3]; if(in.is_open()) { string temp; cout << "Data found in file" << endl; cout << "Storing Pet Rocks into array..." << endl; for(int i = 0; i < 3; i++) { getline(in, data[i].name); in >> data[i].age; getline(in, temp); } // print data cout << endl << "Pet Rocks:" << endl; for(int i = 0; i < 3; i++) { cout << "Name: " << data[i].name << endl; cout << "Age: " << data[i].age << endl << endl << endl; } in.close(); } else { cout << "No data in file" << endl; cout << "Collecting Pet Rocks..." << endl; data[0].name = "Pete"; data[0].age = 1032; data[1].name = "Eugene"; data[1].age = 124832; data[2].name = "Dwayne the Rock"; data[2].age = 2374; cout << "Storing Pet Rocks..." << endl; ofstream out("pet_rocks.txt"); for(int i = 0; i < 3; i++) { out << data[i].name << endl; out << data[i].age << endl; } out.close(); } return 0; }
Get Answers For Free
Most questions answered within 1 hours.