我正在为一个可以插入一本书的图书馆制作一个程序,显示插入的所有书籍,并根据用户插入的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);
}
答案 0 :(得分:1)
你应该改变
ng-model
到
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];
在Frank的评论中指出,对于std::array<Book, 10> book;
,你应该使用与search
相同的类型。
此外,最好将book_code
用于bool
变量:
found
答案 1 :(得分:1)
found
在搜索块开始时未初始化为0.
修订后的代码如下
for (i=0,found=0;i<x && !found; ++i)
if (book[i].book_code == search)
{
found = 1;
position = i;
}