Consider a text file named scores.txt that contains player scores for a game. A possible sample is shown here where Ronaldo’s best score is 10400, Didier’s best score is 9800, etc.
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
Write a function named getHighScore that takes a string reference parameter and an integer reference parameter. The function should scan through the file and set the reference parameters to the name of the player with the highest score and the corresponding score.
C++ program code:
//Header section
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//The getHighScore function takes a string reference
//parameter playerName and an integer reference parameter highScore.
void getHighScore(string& playerName, int& highScore)
{
//Declare variables
string name;
int score;
string highestPlayer;
int highestScore = 0;
//Opens the file named "scores.txt" using an ifstream object.
ifstream inputFile("scores.txt");
//Use a while loop that reads the file line by line,
//extracting the player name and score.
while (inputFile >> name >> score)
{
//checks if the current score is higher than the
//previous highest score. If so, it updates highestPlayer
//and highestScore.
if (score > highestScore)
{
highestPlayer = name;
highestScore = score;
}
}
inputFile.close();
//Finally, the function assigns the values of highestPlayer
//and highestScore to the reference parameters playerName
//and highScore, respectively.
playerName = highestPlayer;
highScore = highestScore;
}
//Program starts with a main function
int main()
{
//Declare variables
string playerName;
int highScore;
//Call the method
getHighScore(playerName, highScore);
//Display the name of the player with the highest score
//and the corresponding score
cout << "The player with the highest score is: " << playerName << endl;
cout << "The highest score is: " << highScore << endl;
return 0;
}
Input file data(scores.txt):
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
Output of the program code:
The player with the highest score is: Pele
The highest score is: 12300