// Attached: HW_6e
// ===========================================================
// File: HW_6e.cpp
// ===========================================================
// Programmer: Elaine Torrez
// Class: CS 1A
// ===========================================================
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
struct Cat
{
char name[20];
int age;
};
// ==== main ===================================================
// This program prompts the user to enter one more cat record
// and appends it to the critters.bin file. Then it reads and
// displays all 4 cat records.
//
// Input:
// 1 cat name and 1 cat age entered by the user.
// critters.bin - A binary file containing Cat objects.
//
// Output:
// All 4 cat records are displayed in columns.
// ===========================================================
int main()
{
ifstream inFile;
ofstream outFile;
Cat cat;
int count;
string tempName;
count = 0;
// open the binary file in append mode
outFile.open("critters.bin", ios::binary | ios::app);
cout << "Enter one more cat" << endl;
cout << "NAME: ";
getline(cin, tempName);
strcpy(cat.name, tempName.c_str());
cout << "AGE: ";
cin >> cat.age;
cin.ignore();
// append one Cat object to the binary file
outFile.write(reinterpret_cast<char *>(&cat), sizeof(cat));
outFile.close();
// open the binary file for reading
inFile.open("critters.bin", ios::binary);
cout << endl;
cout << "Here is a list of all cats:" << endl;
// read and display all 4 Cat objects
while (count < 4)
{
inFile.read(reinterpret_cast<char *>(&cat), sizeof(cat));
cout << setw(10) << left << cat.name << cat.age << endl;
count = count + 1;
}
inFile.close();
cout << endl;
cout << "Press any key to continue . . .";
cin.get();
return 0;
} // end of main()
// ===========================================================