I am attempting to create a function that asks the user for a dvd title they're looking for which is located in a text file of the format:
title:genre:price
There are 10 lines in the text file which all follow that format. I first placed each line into an array with 10 elements.
I have a DVD class that has the function getTitle() which I'm trying to create:
void DVD::getTitle(){
cout << "Type the title of the dvd you're looking for." << endl;
cin >> title;
for(int i = 0; i < 10; i++){ //Loop through the dvd array object.
if(dvd[i].find(title)){ //Test if the title entered is in any of the array elements
cout << "We have " << title << " in stock." << endl;
}
}
cout << "Sorry we don't have that title." << endl;
}
This function is called in main with a DVD class object. I know the find function returns an iterator to the element once it's found, but I can't figure out how to print out the element once it is found. My output simply writes the first word of the title ("Free" in Free Willy) 9 times instead of only when it finds Free Willy in one of the array elements. I also tried using
for(int i = 0; i < 10; i++){ //Loop through the dvd array object.
//Attempt to search each array element up to the colon, and place the
//strings before the colon in dvdTest.
getline(dvd[i], dvdTest, ':');
//Test if the string elements before the colon are the same as the title entered.
if(dvdTest == title){
cout << "We have " << title << " in stock." << endl;
}
}
cout << "Sorry we don't have that title." << endl;
To try and get all of the current array element up to the colon placed into the dvdTest variable, I then tested if(dvdTest == title) before printing out whether the title is in stock. I got an error saying there is no matching function for call to getline, so I figured getline doesn't apply to arrays. I then tried
for(int i = 0; i < file.eof(); i++){ //Loop through the lines in the file.
//Get strings from the current line up to the colon, place into dvdTest.
getline(file, dvdTest, ':');
if(dvdTest == title){ //Test if dvdTest and the title entered are the same.
cout << "We have " << title << " in stock." << endl;
}
}
cout << "Sorry we don't have that title." << endl;
I tried typing Avatar (the 5th title in the text file) and it simply output "Sorry we don't have that title.", so it either didn't find Avatar or it's checking the first line of the file every time it goes through the for loop? Is it possible to accomplish what I'm trying to do in a similar way, or is this the completely wrong approach and I should be doing it a different way?
I've checked all over cplusplus a few hours a day for 3 days now on file usage, getline, find, and I can't figure anything out.