4. Read and run the following example to understand the general method of binary file and string flow operations.
Example 17
#include <strstream> #include <iostream>using namespace std;struct student{ int num; Char name[20]; float score;}; int main () { student stud[3]={1001, "Li", 78,1002, "Wang", 89.5,1004, "Fun",90}; char c[50]; //user-defined character arrays Ostrstream strout (c,30); //build output string stream, associate with array c, buffer length 30 for (int i=0;i<3;i++) //to character array C write 3 student data strout<<stud[i].num<<stud[i].name<<stud[i].score; strout< <ends; //ends is the I/O operator for C + +, insert a ′\\0′ cout<< "Array C:" << c<<endl; //displays characters in array C Ostrstream strout1 (c,40); //at this point, C will be rewritten for (int i=0;i<3;i++) strout1<& lt;stud[i].num<< "" <<stud[i].name<< "" <<stud[i].score; strout1<<ends; //ends is the I/O operator for C + +, insert a ′\\0′ cout<< "Array C:" << c<<endl; //displays characters in array C return 0;}
Operation Result:
15th Week program Reading-binary files and files read 4