I am creating a library database where I read the authors and titles in from a file and store the info in parallel arrays. Then, I am trying to search for specific pieces within that array. For instance, I am reading in the author "Ernest Hemingway" in and storing it in a spot in the author array.
Then I have to be able to search for "Hemingway" and have it pop up with his book that is in the parallel array. My problem is, even if I search for "Ernest", this search won't return "Ernest Hemingway".
Now, part of my code to read the titles and authors is such:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
string bookTitle[1000];
string bookAuthor[1000];
//for loop that will save titles and authors in array
for (int i = 0; i < 1000; i++)
{
//while there are things left to get in file
if(inFile)
{
getline(inFile, bookTitle[i]);
getline(inFile, bookAuthor[i]);
//keep count of number of books
count++;
}
}
int loc = 0; //declare for loop variable
//while loop will continue through array until end of library
while (loc < count)
{
if (bookAuthor[loc] == name)
{
cout << bookTitle[loc] << " (" << bookAuthor[loc] << ")"
<< endl
}
loc++;
}
I have a feeling that my problem is that I'm saving the titles and authors as strings. I think that strings are saved a certain way so you can't search within it. Thus, the name and bookAuthor[loc] will never be equal. What should I do though? What is possible way of coding up a solution to my problem?
Unless I am understanding incorrectly you could simply search the actual array for the author name and then return what resides at that position in the array.
For example (not tested):
1 2 3 4 5 6
/// Function to determine the position in the authors array that the search resides and return the author
std::string FindAuthor(std::string authors[], int size, std::string search) {
for (int i = 0; i < size; i++)
if (authors[i].find(search) != std::string::npos)
return authors[i];
}
TRESKY! YOU'RE A LIFESAVER! I HAVE LITERALLY SPENT 3-4 HOURS TRYING TO GET THIS TO WORK, AND IT WAS WHAT FINISHED MY PROGRAM. I AM SO GRATEFUL TO YOU, AND WISH I COULD BUY YOU A DRINK! CHEERS!