95 lines
2.5 KiB
C++
95 lines
2.5 KiB
C++
|
|
#include <exception>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "Person.h"
|
|
|
|
#include "PersonException.h"
|
|
#include <iostream>
|
|
|
|
using std::cin;
|
|
using std::cout;
|
|
using std::string;
|
|
using std::exception;
|
|
|
|
int main() {
|
|
std::vector<Person *> people;
|
|
Person *personPtr;
|
|
|
|
string namePrompt = "Enter name: ";
|
|
string name;
|
|
string agePrompt = "Enter age: ";
|
|
int age;
|
|
string salaryPrompt = "Enter salary: ";
|
|
int salary;
|
|
|
|
cout << namePrompt;
|
|
cin >> name;
|
|
|
|
while (name != "q") {
|
|
// Set 'personPtr' to nullptr at the beginning
|
|
// of the loop to tell us whether a Person
|
|
// object has been created during this pass
|
|
// through the loop
|
|
personPtr = nullptr;
|
|
|
|
try {
|
|
cout << agePrompt;
|
|
cin >> age;
|
|
|
|
if (!cin) {
|
|
cin.clear();
|
|
string dummy;
|
|
cin >> dummy;
|
|
throw PersonException("invalid age");
|
|
}
|
|
|
|
personPtr = new Person(name, age);
|
|
|
|
cout << salaryPrompt;
|
|
cin >> salary;
|
|
if (!cin) {
|
|
cin.clear();
|
|
string dummy;
|
|
cin >> dummy;
|
|
throw PersonException("invalid salary");
|
|
}
|
|
|
|
personPtr->setSalary(salary);
|
|
|
|
// We only get here if no exception has been
|
|
// raised, that is, both 'age' and 'salary'
|
|
// are valid and non-negative.
|
|
people.push_back(personPtr);
|
|
}
|
|
|
|
catch (exception &e) {
|
|
cout << "PersonException thrown: " << e.what() << '\n';
|
|
|
|
// If an exception was raised, then the current object
|
|
// is invalid and should be deleted. Recall that:
|
|
// 1. delete on a null pointer is harmless (does nothing)
|
|
// 2. delete on a non-null pointer causes that pointer
|
|
// to be set to an undefined value
|
|
delete personPtr;
|
|
// Since 'personPtr' may now be undefined, set it to null.
|
|
personPtr = nullptr;
|
|
}
|
|
|
|
cout << "There are " << Person::GetCount() << " Person(s), " << people.size() << " in vector\n";
|
|
|
|
cout << namePrompt;
|
|
cin >> name;
|
|
}
|
|
|
|
// delete all the person(s) in the vector
|
|
for (std::vector<Person *>::iterator iter = people.begin(); iter != people.end(); ++iter) {
|
|
delete *iter;
|
|
}
|
|
|
|
cout << "There are " << Person::GetCount() << " Person(s) left dangling\n";
|
|
|
|
return 0;
|
|
}
|