Name: John Milton Major: EE GPA: 3.98 Name: Karl Lewis Major: CS GPA: 3.6 Name:
ID: 3547628 • Letter: N
Question
Name: John Milton
Major: EE
GPA: 3.98
Name: Karl Lewis
Major: CS
GPA: 3.6
Name: Homer Simpson
Major: CE
GPA: 4.0
.
.
.
A) Write a program to read and display the file content in the following format:
Name: Major: GPA:
John Milton EE 3.98
Karl Lewis CS 3.6
Homer Simpson CE 4.0
...
B) Count the number of record in the file( A record consist of student name, major and GPA)
C) Write in a file, following the format of the table displayed on A) into a new file named outputFile.txt
D) Optional: Compute the average GPA
E) Optional: Count the number of students from each major
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int studentID, studentCounter=0;
double grade1, grade2, grade3, grade4, course1Sum=0, course2Sum=0, course3Sum=0, course4Sum=0, course1Average, course2Average, course3Average, course4Average, GPA;
ifstream inputFile;
string filename;
for (int x=1; x<=3; x++) {
// Get the filename from the user.
// /Users/etc/Desktop/HW5test.txt - valid set
// /Users/etc/Desktop/HW5testset.txt - test set
cout<<"Enter the filename: ";
cin>>filename;
// Open the file.
inputFile.open(filename.c_str());
// If the file successfully opened, process it.
if (inputFile) {
// Read the numbers from the file and display them.
while (inputFile>>studentID>>grade1>>grade2>>grade3>>grade4)
{
if (studentCounter==0) // Prints header if at the start of the program.
cout<<"Header placeholder"<<endl;
inputFile>>studentID>>grade1>>grade2>>grade3>>grade4;
GPA=(grade1+grade2+grade3+grade4)/4;
cout<<studentID<<" "<<GPA<<" "<<"Special message (if needed)."<<endl;
// Course Average and Student Accumulators
course1Sum+=grade1;
course2Sum+=grade2;
course3Sum+=grade3;
course4Sum+=grade4;
studentCounter++;
}
if (studentCounter==0)
{
// Prints header if at the start of the program.
studentCounter++;
cout<<"Header placeholder"<<endl;
continue;
}
else {
// Perform course averages here, after all data has been read.
course1Average=course1Sum/studentCounter;
cout<<"Course 1 average: "<<course1Average<<endl;
course2Average=course2Sum/studentCounter;
cout<<"Course 2 average: "<<course2Average<<endl;
course3Average=course3Sum/studentCounter;
cout<<"Course 3 average: "<<course3Average<<endl;
course4Average=course4Sum/studentCounter;
cout<<"Course 4 average: "<<course4Average<<endl<<endl;
}
inputFile.close();
}
else {
cout<<"Error opening the file. ";
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.