Jun 22, 2021 at 1:08am Jun 22, 2021 at 1:08am UTC
Hello,
I'd like to if a book not find, the below method(findBookByAuthorName) return NULL. or do you have a better idea?
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
class books
{
book* myBooks;
int i;
public :
books(int n)
{
myBooks = new book[n];
i = 0;
}
void addBook(book Book)
{
myBooks[i] = Book;
i++;
}
book findBookByAuthorName(string name)
{
for (int j = 0; j < i; j++)
{
if (name.compare(myBooks[j].getAuthor()) == 0)
{
return myBooks[j];
}
}
}
}
Last edited on Jun 22, 2021 at 1:09am Jun 22, 2021 at 1:09am UTC
Jun 22, 2021 at 3:48am Jun 22, 2021 at 3:48am UTC
if for some reason you can't use that ^^ the 2 main alternatives would be to make a bogus book to return or to return the array index as -1 for not found, index if found, make the finder int instead of book type, and then you can call THAT from a more public function that handles the -1 or index in a little wrapper for the user. And I guess you could throw and do try/catch, though I find abusing that for non errors to be a bit of a bad idea.
Last edited on Jun 22, 2021 at 3:56am Jun 22, 2021 at 3:56am UTC
Jun 22, 2021 at 8:19am Jun 22, 2021 at 8:19am UTC
You could also return book{}. Then test with book{} to determine if book found or not.
Last edited on Jun 22, 2021 at 8:20am Jun 22, 2021 at 8:20am UTC
Jun 22, 2021 at 1:50pm Jun 22, 2021 at 1:50pm UTC
To return a pointer you'd do:
1 2 3 4 5 6 7 8 9 10 11 12
book * findBookByAuthorName(string name)
{
for (int j = 0; j < i; j++)
{
if (name.compare(myBooks[j].getAuthor()) == 0)
{
return myBooks+j ;
}
}
return nullptr ;
}
}
But dealing with raw pointers like this is a landmine of bugs waiting to happen. So any of the alternatives given is preferable.
Last edited on Jun 22, 2021 at 1:50pm Jun 22, 2021 at 1:50pm UTC