fork download
  1. // Attached: HW_6e
  2. // ===========================================================
  3. // File: HW_6e.cpp
  4. // ===========================================================
  5. // Programmer: Elaine Torrez
  6. // Class: CS 1A
  7. // ===========================================================
  8.  
  9. #include <iostream>
  10. #include <fstream>
  11. #include <string>
  12. #include <cstring>
  13. #include <iomanip>
  14.  
  15. using namespace std;
  16.  
  17. struct Cat
  18. {
  19. char name[20];
  20. int age;
  21. };
  22.  
  23.  
  24. // ==== main ===================================================
  25. // This program prompts the user to enter one more cat record
  26. // and appends it to the critters.bin file. Then it reads and
  27. // displays all 4 cat records.
  28. //
  29. // Input:
  30. // 1 cat name and 1 cat age entered by the user.
  31. // critters.bin - A binary file containing Cat objects.
  32. //
  33. // Output:
  34. // All 4 cat records are displayed in columns.
  35. // ===========================================================
  36.  
  37. int main()
  38. {
  39. ifstream inFile;
  40. ofstream outFile;
  41. Cat cat;
  42. int count;
  43. string tempName;
  44.  
  45. count = 0;
  46.  
  47. // open the binary file in append mode
  48. outFile.open("critters.bin", ios::binary | ios::app);
  49.  
  50. cout << "Enter one more cat" << endl;
  51.  
  52. cout << "NAME: ";
  53. getline(cin, tempName);
  54. strcpy(cat.name, tempName.c_str());
  55.  
  56. cout << "AGE: ";
  57. cin >> cat.age;
  58. cin.ignore();
  59.  
  60. // append one Cat object to the binary file
  61. outFile.write(reinterpret_cast<char *>(&cat), sizeof(cat));
  62.  
  63. outFile.close();
  64.  
  65. // open the binary file for reading
  66. inFile.open("critters.bin", ios::binary);
  67.  
  68. cout << endl;
  69. cout << "Here is a list of all cats:" << endl;
  70.  
  71. // read and display all 4 Cat objects
  72. while (count < 4)
  73. {
  74. inFile.read(reinterpret_cast<char *>(&cat), sizeof(cat));
  75. cout << setw(10) << left << cat.name << cat.age << endl;
  76. count = count + 1;
  77. }
  78.  
  79. inFile.close();
  80.  
  81. cout << endl;
  82. cout << "Press any key to continue . . .";
  83. cin.get();
  84.  
  85. return 0;
  86.  
  87. } // end of main()
  88.  
  89. // ===========================================================
Success #stdin #stdout 0s 5316KB
stdin
NAME:  Luna
AGE:  4
stdout
Enter one more cat
NAME:  AGE:  
Here is a list of all cats:
NAME:  Luna0
NAME:  Luna0
NAME:  Luna0
NAME:  Luna0

Press any key to continue . . .