I have to write a program that allows the user to enter the information for up to 20 students. The info then has to be displayed and written to a file. After I enter the first students info and hit enter it goes nuts. Does anyone see something that I have done wrong?
Code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
class Grade
{
private:
string name;
int exam1, exam2, homework, finalExam;
public:
Grade(){setGrade("Tom", 94, 92, 87 ,85);};
Grade(string nm, int ex1, int ex2, int hw, int final){setGrade(name, ex1, ex2, hw,final);}
void setGrade(string nm, int ex1, int ex2, int hw, int final){name=nm; exam1=ex1; exam2=ex2; homework=hw; finalExam=final;};
string getName(){return name;};
int getExam1(){return exam1;};
int getExam2(){return exam2;};
int getHomework(){return homework;};
int getFinalExam(){return finalExam;};
};
int _tmain(int argc, _TCHAR* argv[])
{
const int Grades = 5;
string filename = "grades.dat";
string name;
ofstream outFile;
int i, exam1, exam2, homework, finalExam;
Grade g;
vector<Grade> gTable;
outFile.open(filename.c_str());
if(outFile.fail())
{
cout << "The file was not successfully opened."<<endl;
exit(1);
}
outFile << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
for(i=0; i<Grades; i++)
{
cout <<"\nEnter students name, 1st exam grade, 2nd exam grade, homework average, and final exam grade (type done to exit): \n";
cin >> name>>exam1>>exam2>>homework>>finalExam;
if(name=="done")
break;
cout <<"\nFor the students the following data has been written to the file: \n";
cout <<name<<" "<<exam1<<" "<<exam2<<" "<<homework<<" "<<finalExam<<endl;
g=Grade(name, exam1, exam2, homework, finalExam);
gTable.push_back(g);
}
for(i=0; i<gTable.size(); i++)
{
outFile <<gTable[i].getName()<<" "
<<gTable[i].getExam1()<<" "
<<gTable[i].getExam2()<<" "
<<gTable[i].getHomework()<<" "
<<gTable[i].getFinalExam()<<endl;
}
outFile.close();
cout << "The file " << filename
<< " has been successfully written." << endl;
cin.ignore();cin.ignore();
return 0;
}
Comment