#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int id;
float gpa;
};
void printStudents(Student* student, int nStudents)
{
int i;
for (i = 0; i < nStudents; i++)
{
cout << "Name = " << left << setw(30) << student[i].name;
cout.fill('0');
cout << " ID = " << right << setw(7)
<< student[i].id << ", gpa = "
<< student[i].gpa << endl;
cout.fill(' ');
}
}
int main()
{
// open a file for input
ifstream fin;
fin.open("students.txt");
if (!fin.good()) throw "I/O error";
// create an empty list
const int MAX_STUDENTS = 100; // capacity
int nStudents = 0; // initially empty
Student student[MAX_STUDENTS];
// read and save the records
while (fin.good())
{
// create a record and read it from file
Student aStudent;
getline(fin, aStudent.name);
fin >> aStudent.id;
fin.ignore(1000, 10);
fin >> aStudent.gpa;
fin.ignore(1000, 10);
fin.ignore(1000, 10); // skip the ---------- separator
// add record to list, if it's not full
if (nStudents < MAX_STUDENTS)
student[nStudents++] = aStudent;
}
fin.close();
// sort the students by name
for (int i = 0; i < nStudents; i++)
{
for (int j = i + 1; j < nStudents; j++)
{
if (student[i].name > student[j].name)
{
Student temp = student[i];
student[i] = student[j];
student[j] = temp;
}
}
}
printStudents(student, nStudents);
return 0;
} // main
Thursday, November 10, 2011
Chap12.3 sample code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment