#include <iostream>
#include <string>
#include <fstream>
constint NUM_SCORES = 5 ;
constint MIN_SCORE = 0 ;
constint MAX_SCORE = 100 ;
std::string get_name() // return the name entered by the user
{
std::string name ;
std::cout << "name: " ;
while( name.empty() ) // skip over any empty input lines
std::getline( std::cin, name ) ;
return name ;
}
int get_score() // return the score entered by the user
{
int score ;
std::cout << "enter score [" << MIN_SCORE << ',' << MAX_SCORE << "]: " ;
if( std::cin >> score ) // if the user entered an integer
{
// if it is in valid range, return it
if( score >= MIN_SCORE && score <= MAX_SCORE ) return score ;
else std::cout << "out of range. try again\n" ;
}
else // the user did not enter a number
{
std::cout << "error: invalid input. try again\n" ;
// handle the input error
// https://en.cppreference.com/w/cpp/io/basic_ios/clear
std::cin.clear() ; // clear the error state of stdin
// https://en.cppreference.com/w/cpp/io/basic_istream/ignore
std::cin.ignore( 1000, '\n' ) ; // throw the bad input line away
}
return get_score() ; // try again
}
// calculate and return the average
// invariant: array holds NUM_SCORES valid scores
double calc_average( constint scores[] ) // note: const
{
// static_assert( NUM_SCORES > 0 ) ; // sanity check
// add up the scores
double total = 0 ;
for( int i = 0 ; i < NUM_SCORES ; ++i ) total += scores[i] ;
// compute the average and return it
return total / NUM_SCORES ;
}
int main()
{
// declare arrays of names and scores
std::string names[NUM_SCORES] ;
int scores[NUM_SCORES] {} ; // , initialised to all zeroes
//set names and score from user input
for( int i = 0 ; i < NUM_SCORES ; ++i )
{
names[i] = get_name() ;
scores[i] = get_score() ;
}
// open and write the scores and average to a file
constchar file_name[] = "average.txt" ;
std::ofstream file(file_name) ; // open the file for output
if( file.is_open() ) // if the file was successfully opened
{
// write the names and scores
for( int i = 0 ; i < NUM_SCORES ; ++i )
file << "name: " << names[i] << " score: " << scores[i] << '\n' ;
//calculate and write the average
constdouble average = calc_average(scores) ;
file << "\n--------------\naverage score: " << average << '\n' ;
}
else std::cout << "error: failed to open output file\n" ;
}
This does not give the average to the main(). The main calls the function with array and stream.
The function performs two tasks:
1. Computes average.
2. Writes the result to a stream.