两个月前,我写了一篇构建一个简易图书馆(C语言),但之后我又分心研究算法,还有应对学校里的课程,就一直没有继续学习有关链表的知识,终于等放寒假了,我又重新回顾以前的知识,作为检测,我打算重新用C++写下构建一个简易图书馆的更新版,也就是下面的内容(当然都只是基础内容)
补充:有关这篇C++写的与C语言写的区别
C语言 | C++ |
---|---|
char 型数组充当字符串 | string 类型 |
scanf 输入 | cin 输入 |
malloc 与 free 申请堆 | new 与 delete申请堆 |
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
struct Book
{
string title;
string author;
struct Book* next;
};
void Input(struct Book* book)
{
cout << "请输入作者:" << endl;
cin >> book->author;
cout << "请输入书名:" << endl;
cin >> book->title;
}
void Add(struct Book** lib)
{
struct Book* book = new struct Book; //C++内存分配方便之处
Input(book);
if (*lib != NULL)
{
book->next = *lib;
*lib = book;
}
else
{
book->next = NULL;
*lib = book;
}
}
void Print(struct Book* lib)
{
struct Book* book = lib;
string ss;
int a = 1;
cout << "请输入你想打印的书籍名 或 作者名" << endl;
cin >> ss;
while (book!=NULL)
{
if (book->author == ss || book->title == ss)
{
cout << "为宁找到的第" << a << "本书:" << endl;
cout << "书名是:" << book->title << endl;
cout << "作者是:" << book->author << endl;
cout << endl;
a++;
}
book = book->next;
}
if (a == 1)
{
cout << "抱歉没有能找到宁所要的书籍" << endl << endl;
}
}
void Release(struct Book** lib)
{
struct Book* book = *lib;
if (book != NULL)
{
delete[] book;
*lib = (*lib)->next;
book = *lib;
}
}
int main()
{
struct Book*Library = NULL;
char ch;
cout << "请录入宁的第一本书籍信息:"<<endl;
do
{
cout << endl;
Add(&Library);
cout<<"请问是否还需要录入书籍信息(Y/N)-->";
do
{
ch = getchar();
} while (ch != 'Y' && ch != 'N');
} while (ch == 'Y');
cout << endl;
cout << "请问是否需要打印图书信息(Y/N)-->";
do
{
ch = getchar();
} while (ch != 'Y' && ch != 'N');
if (ch == 'Y')
{
do
{
Print(Library);
cout << "请问是否还需要打印图书信息(Y/N)-->";
do
{
ch = getchar();
} while (ch != 'Y' && ch != 'N');
} while (ch == 'Y');
}
Release(&Library);
return 0;
}
👇记录一下重新写这篇 《构建一个简易图书馆》 遇到的困难
1、缓存区问题
一开始我一直用 ch = getchar()来记录 Y 和 N ,但运行时总是卡顿( 因为getchar()是读取缓冲区里的内容,也就包括上一次的回车符 ),最后我用do while句式使 ch 只能接收 Y 和 N 才解决了问题
2、结构体声明
其实最初我想用下面这样的句式
typedef struct Book
{
string title;
string author;
struct Book* next;
}Bok;
这样就使 Bok 就代替了 struct Book
代替原来的
struct Book
{
string title;
string author;
struct Book* next;
};
但这样的句式却在我的 VS 2019 上运行不通(也不知道为什么)
3、改进了 Print()函数
在《构建一个简易图书馆(C语言)》中 Print()函数是打印全部书本
而《构建一个简易图书馆(C++)》中 Print()函数是选择打印书本
即使用了搜索链表的方法