// Attached: HW_6d
// ===========================================================
// File: HW_6d.cpp
// ===========================================================
// Programmer: Elaine Torrez
// Class: CS 1A
// ===========================================================
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
struct Cat
{
char name[20];
int age;
};
// ==== main ===================================================
// This program gets information for 3 cats from the user and
// writes each Cat object to a binary file named critters.bin.
//
// Input:
// 3 cat names and 3 cat ages entered by the user.
//
// Output:
// The cat records are written to critters.bin, and a message
// is displayed on the screen.
// ===========================================================
int main()
{
ofstream outFile;
Cat cat;
int count;
string tempName;
count = 0;
// open the binary file for writing
outFile.open("critters.bin", ios::binary);
cout << "Enter 3 cat records." << endl;
// get the information for 3 cats
while (count < 3)
{
cout << "Enter information about a cat:" << endl;
cout << "NAME: ";
getline(cin, tempName);
strcpy(cat.name, tempName.c_str());
cout << "AGE: ";
cin >> cat.age;
cin.ignore();
// write one Cat object to the binary file
outFile.write(reinterpret_cast<char *>(&cat), sizeof(cat));
count = count + 1;
}
outFile.close();
cout << "Record written to file." << endl;
cout << "Press any key to continue . . .";
cin.get();
return 0;
} // end of main()
// ===========================================================