SOURCE FILE: ex1004b.cpp
//
// Example 10.4 b. Program to read golf scores from the file "ex1003.dat"
// (no white space after last score) and to print the winning score and
// player number
//
#include <fstream.h>
#include <iomanip.h>
#include <assert.h>
const int MAX_NUM_PLAYERS = 100; // maximum number of players
int main(void)
{
void ReadScoresFile(int [], int&);
void winner(const int [], int, int&, int&);
int TourneyScore[MAX_NUM_PLAYERS], // array of scores
TourneyNum, // actual number of players
WinningScore, // winning score
WinningPlayer; // player number of winner
ReadScoresFile(TourneyScore, TourneyNum);
winner(TourneyScore, TourneyNum, WinningScore, WinningPlayer);
cout << "The winner is Player #" << WinningPlayer
<< " with a score of " << WinningScore << ".\n";
return 0;
}
//
// Function to read values for an array
// Pre: ex1003.dat is a file of golf scores.
// Post: score is a constant integer array of golf scores.
// NumPlayers is the number of golf scores.
//
void ReadScoresFile(int score[], int& NumPlayers)
{
ifstream GolfFile("ex1003.dat");
assert(GolfFile);
// read values for array score until end of file
NumPlayers = 0;
while ((NumPlayers < MAX_NUM_PLAYERS) &&
(GolfFile >> score[NumPlayers]))
NumPlayers++;
// print error message if too much data for array
if (!GolfFile.eof())
cout << "\nFile contained more than " << MAX_NUM_PLAYERS
<< " scores.\n"
<< "Only the first " << MAX_NUM_PLAYERS
<< " scores will be processed.\n";
GolfFile.close();
}
//
// Example 10.4b. Function to return the winning (minimum)
// score and player number of a golf tournament
// Pre: score is a nonempty constant array of integer golf
// scores with the minimum occurring only once.
// NumPlayers is the number of values in score.
// Post: The winning score (min) and player number
// (MinPlayer) were returned.
//
void winner(const int score[], int NumPlayers,
int& min, int& MinPlayer)
{
min = score[0];
MinPlayer = 1;
for (int player = 1; player < NumPlayers; player++)
if (score[player] < min)
{
min = score[player];
MinPlayer = player + 1;
}
}