/* This program demonstrates * 1. A dynamic struct variable * 2. Dynamic arrays of structs * 3. Working with Files * * C++ programs can interact with files - read data from files instead fo the keyboard * and print data to files instead of the terminal/screen * To work with files, * 1. Create the file variables - > ifstream for input (cin), ofstream for output (cout) * 2. open a file with the file variable -> check if ok * 3. Use the file, just like cin/cout * 4. close them * */ #include #include #include #include using namespace std; /* We use the Date and student structs we created for the previous example, along with the * previously written functions, readDate, printDate, readStudent, and printStudent * * However, the functions have been edited to read from a file and write to a file * Since the file(s) will be opened only once, in main, we have to pass the file * object (ifstream or ofstream variables) into the function. * * Stream variables always pass by reference */ struct Date { int month, day, year; char dayOfWeek[15]; }; struct Student { string name, major; float gpa; long empl; float grades[3]; Date dateOfBirth; }; // If a function uses a structure, it has to be declared after the struct declaration void printDate(Date d, ofstream &); Date readDate(ifstream &); void printStudent(Student s, ofstream &); void readStudent( Student &s, ifstream &); double classAverage(Student *arr, int size); int main() { /* To open an input file, that is, a file that contains data we need to * read into our program, a la cin, we need a variable of type ifstream * Similarly, to open an output file, that contains data that we are * producing in the program, we need a variable of type ofstream. */ ifstream in; ofstream out; in.open("inputFile.txt"); out.open("outputFile.txt"); if(!in) { cout<<"Unable to open input file"<> num; /* Here, we create a dynamic array of structs */ Student *sPtr = new Student[num]; // Once we have declared it, there is no difference in use between a // dynamic array of structs and an in-stack array of structs // read student data from the file for (int i = 0; i < num; i++) { in.ignore(); // Remove the preceding newline readStudent(sPtr[i], in); // use same as previous example } out<<"Printing student details: "<>var.month>> junk>> var.day>>junk>>var.year; return var; } /* This function accepts a structure variable and prints out the details in the structure * We use the dot (.) operator to access individual elements. */ void printStudent( Student s, ofstream & output) { output<>s.gpa; input>>s.empl; for(int i=0; i<3;i++) input>>s.grades[i]; input.getline(s.dateOfBirth.dayOfWeek, 15, ','); input>>s.dateOfBirth.month; input.ignore(); input>>s.dateOfBirth.day; input.ignore(); input>>s.dateOfBirth.year; }