Reputation: 395
I’m making a program for a library that can insert a book , shows all of the book inserted, and search for a spesific book name according to the book_code inserted by the user , i have done 2 of it but the last one ( searching ) wont run as i expected .. If anyone here can help me i would appreciate it so much. heres the code
#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);
}
this is the output now look like
Upvotes: 0
Views: 260
Reputation: 19043
You should change
if(book->book_code[i] == search) // accesses 1-st book, namely book[0]
to
if(book[i].book_code == search) // accesses i-th book
Even better if you can use std::array
then instead of Book book[10];
you could write:
std::array<Book, 10> book;
And noted in his comment Frank, for search
you should use the same type as for book_code
.
Also, that is preferable to use bool
for found
variable:
bool found = false;
Upvotes: 1
Reputation: 114
found
is not initialised to 0 at start of search block.
Revised code follows
for (i=0,found=0;i<x && !found; ++i)
if (book[i].book_code == search)
{
found = 1;
position = i;
}
Upvotes: 1