Your program will first define the following C++ structure: struct StudentRec {
ID: 3639076 • Letter: Y
Question
Your program will first define the following C++ structure:struct StudentRec
{
string Name; // in the format of "Last name, First Name"
string ID;
double GPA;
};
You will then define an array of StudentRec’s. The array size is 10.
You will then open then file "studentrecord.txt", read the file (using the read_a_record ()
function mentioned below) to populate the array you’ve defined. Each line in the file contains one
student record: First Name, Last Name, ID, and GPA. Note that you must check the array
boundary to prevent array overflow if the file contains more records than the array can hold, and
discard the extra records. You will lose 10% of your points if you do not check this.
Note: You need to create and call a function named bool read_a_record(StudentRec&)
to read one record from the file. It returns true if successfully read a record, and return false
if fails (i.e., end of file).
After reading the records into the array, create a function
print_a_record(StudentRec)to print a student record in one line. You then write a loop
to print out the entire array. The output should be formatted like the following:
No. Name ID GPA
--------------------------------------------------------
1 Adams, Jone M123456 3.65
2 Smith, Mike M452355 2.65
3 Ann, Mary M456712 4.00
the file studeentrecord.txt looks like:
Jone Adams M123456 3.65
Mike Smith M452355 2.65
Mary Ann M456712 4.00
Allen Brown M123456 3.65
Mike Davis M452355 2.65
Mary Wilson M456712 4.00
Allen Harris M123456 3.65
Explanation / Answer
#include<fstream>
#include<iomanip>
#include<iostream>
using namespace std;
ifstream myfile("StudentRecords.txt");//Opens file for
struct StudentRec
{
string Name; // in the format of "Last name, First Name"
string ID;
double GPA;
};
bool read_a_record(StudentRec& Record);
void print_a_record(StudentRec Record,int n);
int main()
{
string line;
StudentRec Record [10];
int n=0;
if (myfile)
{
while (getline(myfile,line))
{
if ((n)<10)
{
read_a_record(Record[n]);
n++;
}
}
if (n>0)
{
cout<<"No. Name ID GPA ";
cout<<"------------------------------------ ";
for (int m=0; m<(n); m++)
{
print_a_record(Record[m],m);
}
}
}
else
cout<<"Error opening file. Try AGAIN.";
}
bool read_a_record(StudentRec& Record)
{
string firstname, lastname;
if (myfile)
{
myfile>>firstname;
myfile>>lastname;
string full_name;
full_name=firstname+", "+lastname;
Record.Name=full_name;
myfile>>Record.ID;
myfile>>Record.GPA;
}
else
return false;
}
void print_a_record(StudentRec Record,int n)
{
cout<<left<<setw(4)<<n+1;
cout<<left<<setw(18)<<Record.Name;
cout<<left<<setw(10)<<Record.ID;
cout<<left<<setw(10)<<Record.GPA<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.