如何让C++程序优雅展示多本书籍的标题、作者及出版日期
解决C++书籍信息输入与美观输出问题
你的核心问题是当前代码将标题、作者、日期分开展示,而需要把单本书的信息整合为包含“written by”的格式输出。同时,使用三个独立的vector存储数据容易出现同步问题,建议用结构体封装单本书的信息,让代码更清晰易维护。
修改后的完整代码
#include <iostream> #include <string> #include <vector> using namespace std; // 定义结构体封装单本书的所有信息 struct Book { string title; string author; string publishDate; }; int main () { int n; vector<Book> books; // 用一个vector统一存储所有书籍对象 cout << "Enter the Number of Books: "; cin >> n; cin.ignore(); // 忽略输入数量后的换行符,避免影响后续getline读取 for (int i = 0; i < n; i++) { Book currentBook; cout << "Type the Book's Title: "; getline(cin, currentBook.title); cout << "Type the Book's Author: "; getline(cin, currentBook.author); cout << "Type the Book's Date: "; getline(cin, currentBook.publishDate); books.push_back(currentBook); } // 按类数组格式输出书籍信息 cout << "\n--- 书籍列表 ---" << endl; for (int i = 0; i < books.size(); i++) { cout << "[" << i+1 << "] 《" << books[i].title << "》 written by " << books[i].author << " (" << books[i].publishDate << ")" << endl; } return 0; }
关键修改说明
- 结构体封装:用
struct Book把标题、作者、日期绑定在一起,避免三个独立vector可能出现的不同步问题,代码逻辑更直观。 - 输出格式调整:遍历存储书籍的
vector时,将单本书的所有信息整合输出,格式为[编号] 《标题》 written by 作者 (出版日期),完全符合你需要的类数组展示形式。 - 代码简化:去掉了多余的单独变量,直接用结构体对象接收输入,代码更简洁。
示例输出效果
假设输入2本书:
Enter the Number of Books: 2 Type the Book's Title: C++ Primer Type the Book's Author: Stanley B. Lippman Type the Book's Date: 2012-08-16 Type the Book's Title: Effective C++ Type the Book's Author: Scott Meyers Type the Book's Date: 2005-05-22
输出会是:
--- 书籍列表 --- [1] 《C++ Primer》 written by Stanley B. Lippman (2012-08-16) [2] 《Effective C++》 written by Scott Meyers (2005-05-22)
内容的提问来源于stack exchange,提问作者kenjiharp12
相关产品推荐
相关产品推荐

