I am trying to make a program that takes the name of a restaurant and the ratings for that restaurant (out of 5 stars) and displays how many people gave the restaurant a certain amount of ratings (1, 2, 3, 4, or 5 stars). The data is stored in a text file.
I cannot figure out an efficient way to check each array index for each rating with out writing 145 tests like the one example already in my script. I thought there was a way to address each index in the array individually without actually having to address each index (array[1], array[2], ...)
#include <iostream>
#include <string>
#include <fstream>
int main()
{
const std::string file_name = "restaurant.txt" ;
if( std::ifstream file{file_name} ) // if the file was opened for input
{
std::string restname ;
if( std::getline( file, restname ) ) // if the name was read
{
constexprint NUM_STARS = 5 ;
// array to hold counts of stars ones, twos etc. eg.star_counts[3] == threes
// (there are no zero stars, so we do not use star_counts[0])
int star_counts[ NUM_STARS + 1 ] {} ; // initialise to all zeroes
char rating ; // a rating read from the file
while( file >> rating ) // for each rating read from the file
{
if( rating >= '1' || rating <= '5' ) // if it is a valid rating (one to five)
{
// update the star count. we exploit the fact that '3' - '0' == 3 etc.
constint nstars = rating - '0' ;
++star_counts[nstars] ;
}
else
{
// invalid characters for ratings like 'x', '9' etc are discarded; we just ignore them right now
// we could add code to print an appropriate error message here
}
}
// display answers
std::cout << "restaurant: " << restname << '\n' ;
for( int nstars = 1 ; nstars <= NUM_STARS ; ++nstars )
std::cout << "Number of customers who rated " << nstars << " == " << star_counts[nstars] << '\n' ;
}
}
else
{
std::cerr << "unable to open file " << file_name << '\n' ;
return 1 ;
}
}