fork download
  1. // Attached: HW_6c
  2. // ===========================================================
  3. // File: HW_6c.cpp
  4. // ===========================================================
  5. // Programmer: Elaine Torrez
  6. // Class: CS 1A
  7. // ===========================================================
  8.  
  9. #include <iostream>
  10. #include <fstream>
  11.  
  12. using namespace std;
  13.  
  14.  
  15. // ==== main ===================================================
  16. // This program reads and displays the numbers in results.txt.
  17. // Then it prompts the user to enter 3 more numbers and appends
  18. // them to the same file.
  19. //
  20. // Input:
  21. // results.txt - A text file containing integer values.
  22. // 3 integers entered by the user.
  23. //
  24. // Output:
  25. // The current numbers in the file are displayed, and the new
  26. // numbers are appended to results.txt.
  27. // ===========================================================
  28.  
  29. int main()
  30. {
  31. ifstream inFile;
  32. ofstream outFile;
  33. int count;
  34. int number;
  35. int userNumber;
  36.  
  37. count = 0;
  38.  
  39. // open the file for reading
  40. inFile.open("results.txt");
  41.  
  42. // check if the file opened successfully
  43. if (!inFile)
  44. {
  45. cout << "Error opening file!" << endl;
  46. return 0;
  47. }
  48.  
  49. cout << "Here are the numbers in the file:" << endl;
  50.  
  51. // read and display the current numbers in the file
  52. while (inFile >> number)
  53. {
  54. cout << number << endl;
  55. }
  56.  
  57. inFile.close();
  58.  
  59. cout << endl;
  60. cout << "Enter 3 more numbers:" << endl;
  61.  
  62. // open the file in append mode
  63. outFile.open("results.txt", ios::app);
  64.  
  65. // get 3 more numbers from the user and append them
  66. while (count < 3)
  67. {
  68. cin >> userNumber;
  69. outFile << userNumber << endl;
  70. count = count + 1;
  71. }
  72.  
  73. outFile.close();
  74.  
  75. cout << "The numbers have been written (appended) to results.txt." << endl;
  76. cout << endl;
  77. cout << "Press any key to continue . . .";
  78.  
  79. cin.ignore();
  80. cin.get();
  81.  
  82. return 0;
  83.  
  84. } // end of main()
  85.  
  86. // ===========================================================
Success #stdin #stdout 0.01s 5308KB
stdin
7
12
25
stdout
Error opening file!