I am creating a book database using C++. I am using a book structure which contains all the information for each book that I create. The problem I am having is that I want to be able to search the file I am printing the books to for a specific book based on a user input. I want multiple searches but if I can just get one I should be able to figure out the other searches. This example is how I am trying to search by ISBN #, which is a part of the book structure stored in a char array.

void findByISBN()
{
    char input[80];
    fstream bookIn;
    bool bookFound = 0; 
    Book book;
    int bookNum;

    cout << "Please enter the ISBN# without any dashes: ";
    cin.getline(input,80);

        //create/open the object to use as the inventory file
    bookIn.open("inventory.txt", ios::in | ios::binary);


    //search the file for the correct book
    for(int i = 1; bookFound != 1; i++)
    {

    //Move the position of the get pointer
    bookIn.seekg(sizeof(book) * i, ios::beg);
    //write the data to the book structure
    bookIn.read(reinterpret_cast<char *>(&book),
                    sizeof(book));

    //check for the correct ISBN #
        if ( strcmp ( book.ISBN, input) == 0)
                bookFound = 1;
                bookNum = i;
    }

    bookIn.close();
    bookRead(bookNum);

}

Please help me with this problem. Thanks in advance.
Jonathan

Hi Johnny

Why open the file in binary mode, isn't it a text file created with text editor?

You may check the length of input read in by getline(). Differs it from size of book?

You need to read every line of your file for locating the entered ISBN,
therefore repositioning it with bookIn.seekg(sizeof(book) * i, ios::beg) is not necessary.

I am not that sure of that, but you may also try:

bookIn.read(reinterpret_cast<char *>(book), sizeof(book));

instead of

bookIn.read(reinterpret_cast<char *>(&book), sizeof(book));

Use false and true instead of 0 and 1.

You should show the declaration of Book.

What is BookRead()?

It is also a good idea to put some test prints within your program to check whether
input has correct value, reinterpret_cast works correctly, all book elements contain
correct values etc.

krs,
tesu

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.