fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. struct Applicant {
  6. std::string lastName;
  7. int course;
  8. std::string group;
  9. double averageScore;
  10. };
  11.  
  12. void writeToFile(const std::string& filename) {
  13. std::ofstream file(filename);
  14.  
  15. if (!file) {
  16. std::cerr << "Error opening file for writing";
  17. return;
  18. }
  19.  
  20. int numApplicants;
  21. std::cout << "Enter the number of applicants: ";
  22. std::cin >> numApplicants;
  23.  
  24. for (int i = 0; i < numApplicants; ++i) {
  25. Applicant app;
  26. std::cout << "Enter last name, course, group and average score for applicant " << i+1 << ": ";
  27. std::cin >> app.lastName >> app.course >> app.group >> app.averageScore;
  28. file << app.lastName << " " << app.course << " " << app.group << " " << app.averageScore << std::endl;
  29. }
  30.  
  31. file.close();
  32. }
  33.  
  34. void readFromFile(const std::string& filename) {
  35. std::ifstream file(filename);
  36.  
  37. if (!file) {
  38. std::cerr << "Error opening file for reading";
  39. return;
  40. }
  41.  
  42. std::cout << "List of applicants:" << std::endl;
  43. Applicant app;
  44. while(file >> app.lastName >> app.course >> app.group >> app.averageScore) {
  45. std::cout << app.lastName << " " << app.course << " " << app.group << " " << app.averageScore << std::endl;
  46. }
  47.  
  48. file.close();
  49. }
  50.  
  51. int main() {
  52. const std::string filename = "applicants.txt";
  53.  
  54. writeToFile(filename);
  55. readFromFile(filename);
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout #stderr 0s 5280KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error opening file for writingError opening file for reading