From part 1, you have a bunch of
AccidentRecord
s. Define operators
<<
and
>>
to write/read a record to/from a stream:
std::ostream& operator<<(std::ostream& stream, const AccidentRecord& record)
{
}
std::istream& operator<<(std::istream& stream, AccidentRecord& record)
{
}
You can now iterate over the records and write them to a file.
Next, implement
operator==
to compare records:
bool AccidentRecord::operator==(const AccidentRecord& that)
{
for each field
{
if(this->field != that.field) return false;
}
return true;
}
Finally, derive from
exception
and write a function to import all records from a file where they were saved:
class DuplicateRecordException
(const AccidentRecord& record) : public std::exception
{
DuplicateRecordException(const AccidentRecord& record)
{
std::cout << what() << ":\n";
std::cout << record << '\n';
}
const char* what() const noexcept override
{
return "Duplicate accident record in database";
}
}
void Import(const std::string& path,
std::vector< AccidentRecord >& database)
{
auto file = std::unique_ptr< std::istream >(new std::ifstream(path));
while(!file->eof())
{
AccidentRecord record;
file >> record;
database.push_back(record);
}
file.reset();
if(record[i] == record[j])
{
throw DuplicateRecordException(record[i]);
}
}
That's a sketch. You need to improve it with error handling and so on. And you'll have to write the test harness yourself. I never bother with tests. :)