一个小Library类

#include <vector>
#include <unordered_map>
#include <string>
#include <cstring>
#include <regex>
#include <exception>
#include <iostream>
using namespace std;

// 输入格式错误异常类
class FormatError {
public:
	FormatError(string errormsg, int errorcode) :error_msg_(errormsg), error_code_(errorcode) {};
	void msg() const;

private:
	string error_msg_; // 错误信息
	int error_code_; // 错误码
};

// 输入逻辑错误异常类
class LogicError{ // TAG LogicError
public:
	LogicError(string errormsg, int errorcode,string extra_msg = "") : error_msg_(errormsg), error_code_(errorcode),extra_msg_(extra_msg){};
	void msg() const;

private:
	string error_msg_;
	string extra_msg_; // 额外错误信息,便于精确定位错误
	int error_code_;
};

class Borrower { // TAG Borrowers
public:
	Borrower();

	string borrower_id() const { return borrower_id_; }
	const vector<string>& book_loaned_ids() const; 

	void DisplayRecord() const;
private:

	string borrower_id_;
	string first_name_;
	string last_name_;
	unsigned int book_loaned_;
	vector<string> book_loaned_ids_;
};

class BookRecord { // TAG BookRecord
public:
	BookRecord();

	string book_id() const { return book_id_; }
	void DisplayRecord() const;
	bool loan_out(); // 借出书。若无余量返回false
	bool is_available() const { return number_of_copies_available_ > 0; } // 检查该书是否有余量

private:
	string book_id_;
	string book_title_;
	string author_first_name_;
	string author_last_name_;
	string year_published_;
	unsigned int number_of_copies_;
	unsigned int number_of_copies_available_;
};

class Catalogue { // TAG Catalogue
public:
	Catalogue();
	~Catalogue();

	int number_of_book_record() const { return number_of_book_record_; }

	BookRecord* FindBookRecord(string book_id);

	void DisplayAllRecord() const; // 打印目录下所有书籍信息

private:
	unsigned int number_of_book_record_;
	vector<BookRecord*>pbook_records_;

	unordered_map<string, BookRecord*> keys; // 无序表,便于通过book_id访问书籍信息
};

class Library {  // TAG Library
public:
	// 特殊成员函数
	Library();
	~Library();

	// 接口
	void DisplayNumOfBooksOnLoan() const;
	void DisplayNumOfBookRecord() const;
	void DisplayNumOfBorrowers() const;
	void DisplayRecord(string id, string tpye); // 根据输入的id和类型打印信息。
	void DisplayAllRecords() const;

private:
	bool loan_out(string book_id);

	unsigned int number_of_books_on_loan_;
	unsigned int number_of_borrowers_;
	Catalogue catalogue_;
	vector<Borrower*> pborrowers_; // 存储借书人信息的指针数组

	BookRecord* GetBookRecord(string book_id) { return catalogue_.FindBookRecord(book_id); }
	Borrower* GetBorrower(string borrower_id);
	unordered_map<string, Borrower *> keys; // 无序表,便于通过borrower_id 访问借书人信息
};

void Library::DisplayAllRecords() const{
	cout << "Total number of books on loan:" << number_of_books_on_loan_ << endl;
	cout << "Total number of books in catalogue:" << catalogue_.number_of_book_record() << endl;
	for(auto i:pborrowers_){
		i->DisplayRecord();
	}
	catalogue_.DisplayAllRecord();
}

void Catalogue::DisplayAllRecord() const{
	for(auto i:pbook_records_){
		i->DisplayRecord();
	}
}


void Library::DisplayNumOfBooksOnLoan() const{
	if (number_of_books_on_loan_ == 0) {
		cout << "No books on loan!" << endl;
	}
	else if (number_of_books_on_loan_ == 1) {
		cout << "There is only one book on loan." << endl;
	}
	else {
		cout << "There are " << number_of_books_on_loan_ << " books on loan." << endl;
	}
}

Library::~Library(){
	for (int i = 0; i < number_of_borrowers_;i++){
		delete pborrowers_[i];
	}
}

const vector<string>& Borrower::book_loaned_ids() const {
	return book_loaned_ids_;
}

bool BookRecord::loan_out() {
	if (is_available()) {
		number_of_copies_available_--;
		return true;
	}
	return false;
}

bool Library::loan_out(string book_id) {
	BookRecord* targetbook = GetBookRecord(book_id);
	bool state = targetbook->loan_out();
	return state;
}

void Library::DisplayNumOfBorrowers()const {
	cout << "The number of borrowers is " << pborrowers_.size() << ".\n";
}

void Library::DisplayNumOfBookRecord() const{
	cout << "The number of book record is " << catalogue_.number_of_book_record() << ".\n";
}

BookRecord* Catalogue::FindBookRecord(string book_id) {
	if(keys.count(book_id)){
		return keys[book_id];
	}
	return nullptr;
}

Borrower* Library::GetBorrower(string borrower_id) {
	for (auto i : pborrowers_) {
		if (i->borrower_id() == borrower_id) {
			return i;
		}
	}
	return nullptr;
}

void LogicError::msg() const{
	cout << "RECORD REFUSED." << "Reason:" << error_msg_ << endl;
	cout << "-----------------------------------------------------------------------------" << endl;
	if(error_code_ == 251){
		cout << "The book id " << extra_msg_ << " doesn't exist in the catalogue." << endl;
		cout << "A borrower can't borrow a book that doesn't exist." << endl;
	}
	else if(error_code_ == 252){
		cout << "The borrower id " << extra_msg_ << " has already existed." << endl;
	}
	else if(error_code_ == 253){
		cout << "The book id " << extra_msg_ << " has already existed." << endl;
	}
	else if(error_code_ == 255){
		cout << "There is not enough copies of book " << extra_msg_ << " .";
	}
	else if(error_code_ == 778){
		cout << "One can't borrow more than 5 books at the same time." << endl;
	}
	cout<<"Please check your record, and enter reasonable records later."<<endl; 
	cout << "-----------------------------------------------------------------------------" << endl;
}

void FormatError::msg()const {
	cout << "RECORD REFUSED."  << "Reason:" << error_msg_ << endl;
	cout << "-----------------------------------------------------------------------------" << endl;
	if(error_code_ == 404){
		cout << "There are 5 fields in total needed to be entered and seperated by char \';\'" << endl;
	}
	else if(error_code_ == 20){
		cout << "The id of the book must be started with a capital letter followed with nubmers." << endl;
	}
	else if(error_code_ == 220){
		cout << "The author's name must be seperated by only one space." << endl;
	}
	else if(error_code_ == 320){
		cout << "Year must be reasonable." << endl;
	}
	else if(error_code_ == 420){
		cout << "Number of copies must a positive integer." << endl;
	}
	else if(error_code_ == 3){
		cout << "The id of the borrower must be a five digit number." << endl;
	}
	else if(error_code_ == 6){
		cout << "The borrower's name must be seperated by only one space." << endl;
	}
	else if(error_code_ == 9){
		cout << "The number of books borrower borrowed must be a positive integer." << endl;
	}
	else if(error_code_ == 555){
		cout << "The id of the books borrowed must be started with a capital letter followed with nubmers." << endl;
	}
	else if(error_code_ == 417){
		cout << "Failed to regonize the mistake." << endl;
	}
	cout<<"Please check your record's format, and enter records in right format."<<endl; 
	cout << "-----------------------------------------------------------------------------" << endl;
}

void Library::DisplayRecord(string id, string type){
	if(type == "book records"){
		catalogue_.FindBookRecord(id)->DisplayRecord();
	}
	else if(type == "borrowers"){
		GetBorrower(id)->DisplayRecord();
	}
}

Library::Library() { // TAG Library()
	number_of_books_on_loan_ = 0;

	cout << ">> Please enter the number of borrowers:";

	string temp;
	getline(cin, temp);

	while(!regex_match(temp.c_str(), regex("[0-9]+"))){
		cout << ">> Please enter a number:";
		getline(cin, temp);
	}
	number_of_borrowers_ = stoi(temp);

	pborrowers_.resize(number_of_borrowers_);
	for (int i = 0; i < number_of_borrowers_;i++){
		try{
			pborrowers_[i] = new Borrower;

			// 检查借书人ID是否存在
			for (int j = 0; j < i;j++){
				if(pborrowers_[j]->borrower_id() == pborrowers_[i]->borrower_id()){
					throw LogicError("ID_EXIST!!!", 252, pborrowers_[i]->borrower_id());
				}		
			}

			// 检查借书人记录中书本ID是否存在
			for(auto& j:pborrowers_[i]->book_loaned_ids()){
				if(!catalogue_.FindBookRecord(j)){
					throw LogicError("BOOK_ID_NOT_EXIST!!!",251,j);
				}
			}

			// 检查所借的书是否有余量
			for(auto&j:pborrowers_[i]->book_loaned_ids()){
				if(!catalogue_.FindBookRecord(j)->is_available()){
					throw LogicError("COPIES_NOT_ENOUGH!!!", 255, j);
				}
			}

			// 借书
			for(auto&j:pborrowers_[i]->book_loaned_ids()){
				catalogue_.FindBookRecord(j)->loan_out();
				number_of_books_on_loan_++;
			}
			keys[pborrowers_[i]->borrower_id()] = pborrowers_[i];
			// FIXME debug
		}
		catch(FormatError&e){
			delete pborrowers_[i];
			i--;
		}
		catch(LogicError&e){
			e.msg(); // 逻辑错误不会由该函数调用的函数抛出,故在此打印错误信息
			delete pborrowers_[i];
			pborrowers_[i] = nullptr;
			i--;

		}
	}
}

Catalogue::Catalogue(){
	cout << ">> Please enter the number of book records:";

	string temp;
	getline(cin, temp);

	while(!regex_match(temp.c_str(), regex("[0-9]+"))){
		cout << ">> Please enter a number:";
		getline(cin, temp);
	}

	number_of_book_record_ = stoi(temp);
	pbook_records_.resize(number_of_book_record_);
	for (int i = 0; i < number_of_book_record_; i++) {
		try {
			pbook_records_[i] = new BookRecord;
			// 检查书本ID是否已存在
			for (int j = 0; j < i;j++){
				if(pbook_records_[j]->book_id() == pbook_records_[i]->book_id()){
					throw LogicError("ID_EXIST!!!", 253,pbook_records_[j]->book_id());
				}
			}
			keys[pbook_records_[i]->book_id()] = pbook_records_[i];
		}
		catch (FormatError& e) {
			delete pbook_records_[i];
			i--;
		}
		catch(LogicError& e){
			e.msg();
			delete pbook_records_[i];
			pbook_records_[i] = nullptr;
			i--;
		}
	}
	
}

Borrower::Borrower(){
	cout << ">> Please enter the information of borrower:";
	string text;
	string pattern = R"---((\d{5});([^;\s]+?\s[^;\s]+);(\d+)(;[A-Z]\d+)+)---";
	match_results<string::iterator> results;
	match_results<string::iterator> bad_results;
	getline(cin, text);
	try{
		// 检查输入合法性
		if(!regex_match(text.begin(),text.end(),results,regex(pattern))){ 
			pattern = R"---(([^;]+);([^;]+);([^;]+);([^;]+)(;[^;]+)*)---";
			// 整体格式不合法
			if(!regex_match(text.begin(),text.end(), bad_results, regex(pattern))){
				throw FormatError("Invalid seperator.", 404);
			}
			// 部分格式不合法
			// 检查部分格式合法性
			else{
				vector<regex> pats{
					regex("\\d{5}"),
					regex("[^;\\s]*?\\s[^;\\s]*"),
					regex("\\d*"),
				};
				match_results<string::iterator>::const_iterator iter = bad_results.begin();
				iter++;
				bool error_throwed = 0;
				for (int i = 0; i < 3; i++, iter++){
					cout << iter->str() << endl;
					if(!regex_match(iter->str().c_str(),pats[i])){
						error_throwed = 1;
						throw FormatError("INVALID_FORMAT!!!",3*i+3);
					}
				}
				// 已借书的id格式出错
				if(!error_throwed){
					throw FormatError("INVALID_FORMAT!!!", 555);
				}
			}
		}
		else{ // 输入合法,初始化对象
			regex pats[3]{
				regex(R"---([0-9]{5})---"),
				regex(R"&&&([^;]+?\s[^;]+)&&&"),
				regex(R"666(;\d+)666"),
			};

			string book_id_pattern = "[A-Z]\\d+";
			regex pattern(book_id_pattern);

			// 用正则表达式分割输入数据,并初始化对象。
			match_results<string::iterator> results;
			regex_search(text.begin(),text.end(),results,pats[0]);
			borrower_id_ = results[0];
			regex_search(text.begin(),text.end(),results,pats[1]);
			first_name_ = results.str();
			regex_search(text.begin(),text.end(),results,pats[2]);
			book_loaned_ = stoi(results.str().substr(1,results.str().size()-1));

			// 用正则表达式分割借书人名字
			regex_match(first_name_.begin(), first_name_.end(), results, regex(R"---((.+)\s(.+))---"));
			first_name_ = results[1];
			last_name_ = results[2];

			// 用正则表达式获取输入中所有book_id,存入到book_loaned_ids_数组
			string temp;
			auto iter_start = text.begin();
			auto iter_end = text.end();
			while(regex_search(iter_start,iter_end,results,pattern)){
				temp = results[0];
				book_loaned_ids_.push_back(temp);
				iter_start = results[0].second; // 搜索剩下的字符串
			}

			// 检查是否有借书过多、借书数量和输入中book_id数量不符等错误。
			if(book_loaned_ids_.size()>5){
				throw LogicError("TOO_MANY_BOOK_LOANED!!!", 778);
			}
			if(book_loaned_!= book_loaned_ids_.size()){
				cout << "Number of book loaned h12345;Joe Bloggs;3;N1234;A251;Z00124as been set to " << book_loaned_ids_.size() << endl;
				cout << "The record has been repaired." << endl;
				cout << "You can edit the record mannully later." << endl;
				book_loaned_ = book_loaned_ids_.size();
			}	
		}
	}
	catch(FormatError &e){
		e.msg();
		throw; // 向Library()函数抛出异常,重新获取输入
	}
	catch(LogicError&e){
		throw; // 向Library()函数抛出异常,重新获取输入
	}
}

Catalogue::~Catalogue(){
	for (int i = 0; i < number_of_book_record_;i++){
		delete pbook_records_[i];
	}
}

void Borrower::DisplayRecord()const {
	cout << "================" << endl;
	cout << "borrower id: " << borrower_id_ << endl;
	cout << "first name: " << first_name_ << endl;
	cout << "last name: " << last_name_ << endl;
	cout << "book loaned: " << book_loaned_ << endl;
	cout << "Here are the books this person borrowed:" << endl;
	for (auto& be : book_loaned_ids_) {
		cout << be << endl;
	}
	cout << "================" << endl;
}

void BookRecord::DisplayRecord() const {
	cout << "================" << endl;
	cout << "book id: " << book_id_ << endl;
	cout << "book title: " << book_title_ << endl;
	cout << "author's first name: " << author_first_name_ << endl;
	cout << "author's last name: " << author_last_name_ << endl;
	cout << "year published: " << year_published_ << endl;
	cout << "number of copies: " << number_of_copies_ << endl;
	cout << "number of copies avaliable: " << number_of_copies_available_ << endl;
	cout << "================" << endl;
}

// TAG BookRecord()
BookRecord::BookRecord() {
	cout << ">> Please enter the book record data:";
	string text;
	string pattern = R"---(([A-Z]\d+);([^;]+);([^;\s]+\s[^;\s]+);(\d{1,4});(\d+))---";
	vector<string> fields;
	match_results<string::iterator> results;
	match_results<string::iterator> bad_results;

	getline(cin, text);

	try {
		// 检查输入合法性
		if (!regex_match(text.begin(), text.end(), results, regex(pattern))) {
			pattern = R"---(([^;]+);([^;]+);([^;]+);([^;]+);([^;]+))---";
			// 检查输入中数据域数量是否正确
			if (!regex_match(text.begin(), text.end(), bad_results, regex(pattern))) {
				throw FormatError("INVALID_SEPERATOR!!!", 404);
			}

			// 部分数据域格式不正确,逐个检查格式
			else {
				vector<string> pats{
					"([A-Z]\\d+)",
					"([^;]+?)",
					"([^;\\s]+\\s[^;\\s]+?)",
					"(\\d{1,4})",
					"(\\d+)",
				};

				match_results<string::iterator>::const_iterator iter = bad_results.begin()+1;

				for (int i = 0; i < 5; i++, iter++) {
					string temp = iter->str();
					if (!regex_match(temp.begin(), temp.end(), regex(pats[i]))) {
						throw FormatError("INVALID_FORMAT!!!", i * 100 + 20);
					}
				}
			}
			// 未识别到的格式错误 (在测试中没有抛出过)
			throw FormatError("UNKNOWN_ERROR!!!", 417);
		}
		else { // 输入合法,初始化对象
			for (auto iter = results.begin()++; iter !=results.end(); iter++){
				fields.push_back(iter->str());
			}
			book_id_ = fields[1];
			book_title_ = fields[2];
			author_first_name_ = fields[3];

			// 用substr()方法分割作者名。Borrower类中的实现是正则表达式,会比较方便
			for (int i = 0; i < author_first_name_.size();i++){
				if(author_first_name_[i] == ' '){
					author_last_name_ = author_first_name_.substr(i+1, author_first_name_.size() - i);
					author_first_name_ = author_first_name_.substr(0, i);
					break;
				}
			}
			// 检查年份
			year_published_ = fields[4];
			if(stoi(year_published_) > 2022||stoi(year_published_) <= 1000)
				throw FormatError("INVALID_FORMAT!!!", 320);	

			number_of_copies_ = stoi(fields[5]);
			number_of_copies_available_ = number_of_copies_;
		}
	}
	catch (FormatError&e) {
		e.msg();
		throw; // 向resize()函数抛出异常,重新获取输入
	}
}

int main() {
	string head = "********Library Manage System********\n";

	cout << head;
	Library hahaha;

	// 打印初始信息
	hahaha.DisplayAllRecords();
}

表面上看这是学校布置的面向对象编程作业

但其实这是一个正则表达式demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值