1022 Digital Library (30 分)

mac2026-05-12  9

1022 Digital Library (30 分)

思想

结构体去做 自定义排序方式实现从小到大编号 存储string的vector的使用 有点小坑是编号的7位输出 PTA老把戏 substr的使用截取查询段 cin.peek()窥视实现多个keyword的获取 输入方面cin.get()有点小讲究 如果要用cin 无需使用 因为cin是智能指针可以跳过缓冲区的无效字符(如空格、回车) 如果要用getline 则需要加一个cin.get()在下一次读取前清空残余缓存 getline与getline之间无需使用cin.get() 剩下的慢慢模拟吧 到这里讲解结束

AC代码

#include <iostream> #include <cstdio> #include <vector> #include <string> #include <algorithm> using namespace std; struct book{ int id; string title; string author; vector<string> keywords; string publisher; string year; }books[10010]; bool cmp(book a, book b){ return a.id < b.id; } int n; string qword; void q1(){ string qtitle = qword.substr(3); int flag = 0; cout << qword << endl; for (int i = 0; i < n; i++){ if (qtitle == books[i].title){ flag = 1; printf("%07d\n", books[i].id); } } if (!flag) cout << "Not Found" << endl; } void q2(){ string qauthor = qword.substr(3); int flag = 0; cout << qword << endl; for (int i = 0; i < n; i++){ if (qauthor == books[i].author){ flag = 1; printf("%07d\n", books[i].id); } } if (!flag) cout << "Not Found" << endl; } void q3(){ string qkeyword = qword.substr(3); int flag = 0; cout << qword << endl; for (int i = 0; i < n; i++){ for (int j = 0; j < books[i].keywords.size(); j++){ if (qkeyword == books[i].keywords[j]){ flag = 1; printf("%07d\n", books[i].id); break; } } } if (!flag) cout << "Not Found" << endl; } void q4(){ string qpublisher = qword.substr(3); int flag = 0; cout << qword << endl; for (int i = 0; i < n; i++){ if (qpublisher == books[i].publisher){ flag = 1; printf("%07d\n", books[i].id); } } if (!flag) cout << "Not Found" << endl; } void q5(){ string qyear = qword.substr(3); int flag = 0; cout << qword << endl; for (int i = 0; i < n; i++){ if (qyear == books[i].year){ flag = 1; printf("%07d\n", books[i].id); } } if (!flag) cout << "Not Found" << endl; } int main(){ cin >> n; for (int i = 0; i < n; i++){ cin >> books[i].id; cin.get(); getline(cin, books[i].title); getline(cin, books[i].author); while (cin.peek() != '\n'){ string key; cin >> key; books[i].keywords.push_back(key); } cin.get(); getline(cin, books[i].publisher); cin >> books[i].year; } sort(books, books+n, cmp); int query; cin >> query; cin.get(); while (query--){ getline(cin, qword); switch (qword[0]){ case '1': q1(); break; case '2': q2(); break; case '3': q3(); break; case '4': q4(); break; case '5': q5(); break; }; } return 0; }
最新回复(0)