C++ Write a program that reads students’ names followed by their test scores fro
ID: 3677829 • Letter: C
Question
C++
Write a program that reads students’ names followed by their test scores from the given input file. The program should output to a file, output.txt, each student’s name followed by the test scores and the relevant grade.
Student data should be stored in a struct variable of type StudentType, which has four components: studentFName and studentLName of type string, testScore of type int and grade of type char. Suppose that the class has 20 students. Use an array of 20 components of type StudentType. Your program must contain at least the following functions:
A function to read the students’ data into an array.
A function to assign the relevant grade to each student.
Your program should output each student’s name in this form: last name followed by a comma, followed by a space, followed by the first name; the name must be left justified. Moreover, other than declaring the variables and opening the input and output files, the function main should only be a collection of function calls.
This is the students information:
Mike Noel 88
John Smith 98
Emma Watson 58
Harry Potter 68
Ron Weasley 75
Alex Roark 98
Tom Sawyer 94
Huck Finn 92
Explanation / Answer
Please find the required code below :
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
struct studentType
{
string studentFName;
string studentLName;
char grade;
int testScore;
};
char getGrade(int score){
char g;
if(score > 80)
g = 'A';
else if(score > 60)
g = 'B';
else if(score > 50)
g = 'C';
else if(score > 40)
g = 'D';
else
g = 'F';
return g;
}
studentType * readData(){
studentType students[20];
string arr[7];
int i = 0;
ifstream input( "filename.ext" );
for( std::string line; getline( input, line ); )
{
stringstream ssin(line);
while (ssin.good() && i < 7){
ssin >> arr[i];
++i;
}
struct studentType s;
s.studentFName = arr[0];
s.studentLName = arr[1];
s.testScore = stoi(arr[2]);
s.grade = getGrade(s.testScore);
students[i] = s;
}
return students;
}
int main( )
{
studentType * students;
students = readData();
ofstream myfile;
myfile.open ("output.txt");
for(int i=0; i<20; i++){
myfile << students[i].studentLName <<", " << students[i].studentFName << " " << students[i].grade << endl;;
}
myfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.