Mobile Apps with Qt: Rui's solution to hw4

From CSclasswiki
Jump to: navigation, search

personClass.h

// personClass.h

#ifndef personClass_h
#define personClass_h
#include <string>
#include <vector>

using namespace std;

class personClass {
 private :
  string name;
  vector<float> grades;
  float GPA;

 public:
  // constructor
  personClass() {
    name = "";
    vector<float> grades(0);
    GPA = 0;
  }

  personClass(string n) {
    name = n;
    vector<float> grades(0);
    GPA = 0;
  }

  ~personClass();

  // member functions
  string getName();
  void addGrade(float);
  float getGPA();
  void print();

};

#endif

personClass.cpp

// personClass.cpp

#include <iostream>
#include "personClass.h"
#include <string>

using namespace std;

// destructor
personClass::~personClass() {}

string personClass::getName() {
  return name;
}

void personClass::addGrade(float g) {
  grades.push_back(g);
}

float personClass::getGPA() {
  float sum = 0;
  for (int i = 0; i < grades.size(); i++) {
    sum = sum + grades[i];
  }
  GPA = sum/grades.size();
  return GPA;
}

void personClass::print() {
  cout << name << ": " << grades.size() << " grades: " ;
  for (int i = 0; i < grades.size();i++) {
    cout <<  grades[i] << " ";
  }
  cout << "  " << "GPA= " << getGPA() <<endl;
}

hw4.cpp

// hw4.cpp
// Rui Huang

#include <string>
#include <iostream>
#include <fstream>
#include <strstream>
#include <vector>
#include "personClass.h"

using namespace std;

int main() {
  string filename,line, name;

  // open the grade file
  cout << "Enter the name of the file: " << endl;
  cin >> filename;
  cout << endl;
  ifstream inFile(filename.c_str());
  if (!inFile) {
    cerr << "Error: unable to open file " << filename << endl;
    exit(1);
  }

  int space;
  float x;
  string grades, all;
  vector<personClass> people;
  personClass p;
  while (!inFile.eof()) {
    getline(inFile, line);
    space = line.find(" ");
    name = line.substr(0,space);;
    grades = line.substr(space);
    strstream cio;
    cio << grades;
    // if find the name
    if (all.find(name) != string::npos) {
      for (int i = 0; i < people.size(); i++) {
        if (people[i].getName() == name) {
          while (cio >> x) {
            people[i].addGrade(x);
          }
        }
      }
    }
    else {
      all = all + name;
      p = personClass(name);
      while (cio >> x) {
	p.addGrade(x);
      }
    people.push_back(p);
    }
  }  
  inFile.close();

  for (int i = 0; i < people.size(); i++) {
    people[i].print();
  }

  return 0;
}

Makefile

# macros
CC=g++
CFLAGS=-g -Wall

#--- explicit rules ---
all: hw4

hw4: hw4.cpp personClass.o
	$(CC) $(CFLAGS) -o hw4 hw4.cpp personClass.o

personClass.o: personClass.cpp personClass.h
	$(CC) $(CFLAGS) -c personClass.cpp