fork download
  1. // If you are not sure what some lines of code do, try looking back at
  2. // previous example programs, notes, or ask a question.
  3.  
  4. #include <iostream>
  5. #include <fstream>
  6.  
  7. using namespace std;
  8.  
  9. // Define a student structure data type
  10. struct student {
  11. char* firstName;
  12. char* lastName;
  13. char gender;
  14. float gpa;
  15. };
  16.  
  17. // Function prototypes that work with students
  18. void inputStudents(const char*,student*);
  19. void displayStudents(student*);
  20.  
  21. int main() {
  22.  
  23. // Dynamically allocate five students
  24. student* students = new student[5];
  25.  
  26. inputStudents("students.txt",students);
  27.  
  28. displayStudents(students);
  29.  
  30. // Remember that this memory was allocated in inputStudents(),
  31. // and is still accessible through the student instances.
  32. for(int i = 0; i < 5; i++) {
  33. delete[] students[i].firstName;
  34. delete[] students[i].lastName;
  35. }
  36.  
  37. system("pause");
  38. return 0;
  39. }
  40.  
  41. void inputStudents(const char* fileName,student* data) {
  42. ifstream fin(fileName);
  43.  
  44. for(int i = 0; i < 5; i++) {
  45. // Allocate the memory for each name. Note this is not
  46. // exactly sized, as we specify the max size of 10.
  47. data[i].firstName = new char[10];
  48. data[i].lastName = new char[10];
  49.  
  50. // Input data
  51. fin >> data[i].firstName >> data[i].lastName >> data[i].gender >> data[i].gpa;
  52. }
  53. }
  54.  
  55. void displayStudents(student* data) {
  56.  
  57. for(int i = 0; i < 5; i++) {
  58. cout << "Student " << i << " : ";
  59.  
  60. // Output data for each student
  61. cout << data[i].firstName << " " << data[i].lastName
  62. << " " << data[i].gender << " " << data[i].gpa
  63. << endl;
  64. }
  65. }
  66.  
Success #stdin #stdout #stderr 0s 3464KB
stdin
Standard input is empty
stdout
Student 0 : $��   0
Student 1 :    0
Student 2 :  ����  0
Student 3 :    0
Student 4 :    0
stderr
sh: 1: pause: not found