我正在为一个可以插入一本书的图书馆制作一个程序,显示所有插入的书,并根据用户插入的book_code搜索一个特殊的书名,我已经完成了其中的 2 个,但最后一个(搜索(不会按预期运行..如果这里有人可以帮助我,我将不胜感激。这是代码
#include <iostream>
#include <conio.h>
void show_book(const Book &book );
void input_book (Book &book);
int main ()
{
Book book[10];
int i,x;
char search;
int position,found;
cout<<"How many book you want to add = "; cin>>x;
for (i=0; i<x; i++){
input_book(book[i]);
}
for(i=0; i<x; i++){
show_book(book[i]);
}
//this is my searching code , im stuck here ..
cout<<"n====== SEARCH ====="<<endl;
cout <<"Enter book code = "; cin>>search;
for (i=0; i<x; i++){
if(book->book_code[i] == search){
found = 1;
position = i;
i = x;
}
}
if (found != 0){
show_book(book[position]);
} else{
cout<<"The book is not exist";
}
return 0;
}
//function declaration...
void show_book(const Book &book){
cout<<book.book_code<<" | "<<book.book_title<<endl;
}
void input_book(Book &book){
cout << "Book code : ";cin >> book.book_code;
cin.ignore(1, 'n');
cout << "Book title : " ;getline(cin, book.book_title);
}
这是现在的输出看起来像
found
在搜索块开始时未初始化为 0。
修订后的代码如下
for (i=0,found=0;i<x && !found; ++i)
if (book[i].book_code == search)
{
found = 1;
position = i;
}
你应该改变
if(book->book_code[i] == search) // accesses 1-st book, namely book[0]
自
if(book[i].book_code == search) // accesses i-th book
如果你可以使用std::array
,那就更好了,而不是Book book[10];
你可以写:
std::array<Book, 10> book;
并在他的评论中指出弗兰克,对于search
,您应该使用与book_code
相同的类型.
此外,最好对变量使用bool
found
:
bool found = false;