feat(cmat): Completed Ex61 Part 1

This commit is contained in:
2026-10-08 10:08:48 +02:00
parent 058179b643
commit 4e2e5f72a2
+69 -75
View File
@@ -1,75 +1,69 @@
#include <exception> #include <exception>
#include <string> #include <memory>
#include <vector> #include <string>
#include <vector>
#include "Person.h"
#include "Person.h"
#include "PersonException.h"
#include <iostream> #include "PersonException.h"
#include <iostream>
using std::cin;
using std::cout; using std::cin;
using std::string; using std::cout;
using std::exception; using std::string;
using std::exception;
int main() {
std::vector<Person *> people; int main() {
std::vector<std::shared_ptr<Person>> people;
string namePrompt = "Enter name: ";
string name; string namePrompt = "Enter name: ";
string agePrompt = "Enter age: "; string name;
int age; string agePrompt = "Enter age: ";
string salaryPrompt = "Enter salary: "; int age;
int salary; string salaryPrompt = "Enter salary: ";
int salary;
cout << namePrompt;
cin >> name; cout << namePrompt;
cin >> name;
while (name != "q") {
try { while (name != "q") {
cout << agePrompt; try {
cin >> age; cout << agePrompt;
cin >> age;
if (!cin) {
cin.clear(); if (!cin) {
string dummy; cin.clear();
cin >> dummy; string dummy;
throw PersonException("invalid age"); cin >> dummy;
} throw PersonException("invalid age");
}
Person *personPtr = new Person(name, age);
auto personPtr = std::make_shared<Person>(name, age);
cout << salaryPrompt;
cin >> salary; cout << salaryPrompt;
if (!cin) { cin >> salary;
cin.clear(); if (!cin) {
string dummy; cin.clear();
cin >> dummy; string dummy;
throw PersonException("invalid salary"); cin >> dummy;
} throw PersonException("invalid salary");
}
personPtr->setSalary(salary);
personPtr->setSalary(salary);
people.push_back(personPtr);
} people.push_back(personPtr);
}
catch (exception &e) {
cout << "PersonException thrown: " << e.what() << '\n'; catch (exception &e) {
} cout << "PersonException thrown: " << e.what() << '\n';
}
cout << "There are " << Person::GetCount() << " Person(s), " << people.size() << " in vector\n";
cout << "There are " << Person::GetCount() << " Person(s), " << people.size() << " in vector\n";
cout << namePrompt;
cin >> name; cout << namePrompt;
} cin >> name;
}
// delete all the person(s) in the vector
for (std::vector<Person *>::iterator iter = people.begin(); iter != people.end(); ++iter) { return 0;
delete *iter; }
}
cout << "There are " << Person::GetCount() << " Person(s) left dangling\n";
return 0;
}