Answer:
To read information from a file and sort it by title and search for a specific movie in C++, you need to implement the functions storeMoviesArray, sortMoviesTitle, printMoviesArray, and findMovieTitle. The main function takes care of opening and closing the file, and calling the other functions.
Here is an example implementation:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct Movie {
string title;
int yearReleased;
double revenue;
};
void storeMoviesArray(ifstream& inFile, Movie topMovies[], const int SIZE) {
int count = 0;
while (inFile >> topMovies[count].title >> topMovies[count].yearReleased >> topMovies[count].revenue) {
count++;
if (count == SIZE) {
break;
}
}
}
void sortMoviesTitle(Movie topMovies[], const int SIZE) {
sort(topMovies, topMovies + SIZE, [](const Movie& a, const Movie& b) {
return a.title < b.title;
});
}
void printMoviesArray(Movie topMovies[], const int SIZE) {
for (int i = 0; i < SIZE; i++) {
cout << topMovies[i].title << " (" << topMovies[i].yearReleased << "), " << "$" << topMovies[i].revenue << endl;
}
}
int findMovieTitle(Movie topMovies[],const int SIZE, string title) {
int start = 0;
int end = SIZE - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (topMovies[mid].title == title) {
return mid;
}
else if (topMovies[mid].title < title) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return -1;
}
int main() {
const int SIZE = 20;
Movie topMovies[SIZE];
ifstream inFile("movies.txt");
if (!inFile) {
cerr << "Cannot open file.\\";
return 1;
}
storeMoviesArray(inFile, topMovies, SIZE);
inFile.close();
sortMoviesTitle(topMovies, SIZE);
printMoviesArray(topMovies, SIZE);
cout << endl;
string title;
cout << "
Step-by-step explanation: