fork download
  1. // Attached: HW_6d
  2. // ===========================================================
  3. // File: HW_6d.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.  
  14. using namespace std;
  15.  
  16. struct Cat
  17. {
  18. char name[20];
  19. int age;
  20. };
  21.  
  22.  
  23. // ==== main ===================================================
  24. // This program gets information for 3 cats from the user and
  25. // writes each Cat object to a binary file named critters.bin.
  26. //
  27. // Input:
  28. // 3 cat names and 3 cat ages entered by the user.
  29. //
  30. // Output:
  31. // The cat records are written to critters.bin, and a message
  32. // is displayed on the screen.
  33. // ===========================================================
  34.  
  35. int main()
  36. {
  37. ofstream outFile;
  38. Cat cat;
  39. int count;
  40. string tempName;
  41.  
  42. count = 0;
  43.  
  44. // open the binary file for writing
  45. outFile.open("critters.bin", ios::binary);
  46.  
  47. cout << "Enter 3 cat records." << endl;
  48.  
  49. // get the information for 3 cats
  50. while (count < 3)
  51. {
  52. cout << "Enter information about a cat:" << endl;
  53.  
  54. cout << "NAME: ";
  55. getline(cin, tempName);
  56. strcpy(cat.name, tempName.c_str());
  57.  
  58. cout << "AGE: ";
  59. cin >> cat.age;
  60. cin.ignore();
  61.  
  62. // write one Cat object to the binary file
  63. outFile.write(reinterpret_cast<char *>(&cat), sizeof(cat));
  64.  
  65. count = count + 1;
  66. }
  67.  
  68. outFile.close();
  69.  
  70. cout << "Record written to file." << endl;
  71. cout << "Press any key to continue . . .";
  72. cin.get();
  73.  
  74. return 0;
  75.  
  76. } // end of main()
  77.  
  78. // ===========================================================
Success #stdin #stdout 0.01s 5288KB
stdin
Whiskers
3
Milo
2
Luna
4
stdout
Enter 3 cat records.
Enter information about a cat:
NAME:  AGE:  Enter information about a cat:
NAME:  AGE:  Enter information about a cat:
NAME:  AGE:  Record written to file.
Press any key to continue . . .