14.14 Structure - read and print structure
Assuming you have the following structure
struct Student { int id; string name; float GPA; };
You are required to read students' information from an input file whose filename is provided by standard input; Please use std::cout to output students' name who have a GPA > 3.0 in the reversed order.
input
id=1234567 name=Peter GPA=3.6 id=1234568 name=Adina GPA=3.8 id=1234569 name=Mike GPA=3.0 id=1234569 name=Gina GPA=2.9
Note: input file may be empty.
output
Adina Peter
step 1, count the numbers
step 2, create a dynamic array
step 3, read information into the created dynamic array
step 4, writer students' names in the reversed order to the screen
Code :
Instruction:
Count of data is done using getline.
Then dynamic array created and data stored in that array.
Then data retrieved for GPA > 3.0 and for reverse order that is accessed from last index.
Input the file name with extension as shown in output image.
---------------------------------------------------------------------------------------------------------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
struct Student {
int id;
string name;
float GPA;
};
int main()
{
string inpfile,temp;
cout<<"Enter the file name with
extension:"<<endl;
cin>>inpfile;
ifstream fileData;
fileData.open(inpfile);
if(!fileData)
{
cout<<"Error in file opening."<<endl;
return -1;
}
int noOfData = 0;
while(getline(fileData, temp))
{
noOfData++;
}
Student* studentData = new Student[noOfData];
for(int i=0;i<noOfData;i++)
{
fileData>>studentData[i].id>>studentData[i].name>>studentData[i].GPA;
}
for(int i = (noOfData-1); i >=0; i--)
{
if(studentData[i].GPA > 3.0)
{
cout<<studentData[i].name<<endl;
}
}
delete [] studentData;
fileData.close();
return 0;
}
Code image 1
Code image 2
Code image 3
Data image
Output image
Get Answers For Free
Most questions answered within 1 hours.