c++ project You have collected a file of movie ratings where each movie is rated
ID: 3838724 • Letter: C
Question
c++ project
You have collected a file of movie ratings where each movie is rated from 1 (bad) to 5 (excellent). The first line of the file is a number that identifies how many ratings are in the file. Each rating then consists of two lines: the name of the movie followed by the numeric rating from 1 to 5. Here is a sample rating file with four unique movies and seven ratings:
7
Harry Potter and the Order of the Phoenix
4
Harry Potter and the Order of the Phoenix
5
The Bourne Ultimatum
3
Harry Potter and the Order of the Phoenix
4
The Bourne Ultimatum
4
Wall-E
4
Glitter
1
Write a program that reads a file in this format, calculates the average rating for each movie, and outputs the average along with the number of reviews. Here is the desired output for the sample data:
Glitter: 1 review. Average of 1 / 5
Harry Potter and the Order of the Phoenix: 3 reviews, average of 4.3 / 5
The Bourne Ultimatum: 2 review, average of 3.5 / 5
Wall-E: 1 review. Average of 4 / 5
Use a map of multiple maps to calculate the output. Your map(s) should index from a string representing each movie’s name to integers that store the number of reviews for the movie and the sum of the ratings for the movie.
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
int main()
{
string line;
ifstream my_file("file.txt");
if(my_file.is_open())
{
string::size_type sz;
getline(my_file,line);
int n = stoi(line, &sz);
int x,cnt=0,cur;
map<string, int> mp_index; //Map to store index from string to number
map<int, int> mp_tot_score; //Map to store total sum of review scores
map<int, int> mp_num; //Map to store total number of reviews
for(int i=0;i<n;i++)
{
getline(my_file, line);
if(mp_index.find(line) == mp_index.end())
mp_index[line] = cnt++;
cur = mp_index[line];
getline(my_file, line);
x = stoi(line,&sz);
if(mp_num.find(cur) == mp_num.end())
{
mp_num[cur] = 1;
mp_tot_score[cur] = x;
}
else
{
mp_num[cur] += 1;
mp_tot_score[cur] += x;
}
}
for(auto it:mp_index)
{
cout<<it.first<<": "<<mp_num[it.second]<<" review(s). Average of "<<(float(mp_tot_score[it.second]))/(float(mp_num[it.second]))<<"/5"<<endl;
}
}
else
cout<<"Error opening the file";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.