In C++, First, you must read the results from a data file and store the values u
ID: 3786308 • Letter: I
Question
In C++,
First, you must read the results from a data file and store the values using vectors. The file has the last name of each candidate and the number of votes received on one line. There could be any number of lines in the file so count them as you go.
Finally, you must print the results arranged in order from the winner down to the person with the fewest votes. The report should include only the name of each candidate, the total votes received by that candidate and the percentage of the votes cast in the election for that candidate – arranged in order from largest to smallest. Print the percentages with one decimal place.
Create the data file using the following records and put it into the project folder:
Candidate Votes
Lincoln 5000
Parks 2000
Shakespeare 8000
Ghandi 2500
Ashe 1750
A Sample output is as follows:
Candidate Votes Received % Votes
xxxxxxxxxxxx xxxx xx.x
xxxxxxxxxxxx xxxx xx.x
xxxxxxxxxxxx xxxx xx.x
Please upload the following:
The class .cpp file
The main program
The class .h file
Output File
Explanation / Answer
C++ Program:
#include <iostream>
#include <string>
using namespace std;
int findWinner(int votes[]);
void printResults(string candidates[], int votes[]);
double calculatePercentage(int votes[], int vote);
const int MAX = 5;
int main()
{
string candidates[MAX];
int votes[MAX];
cout << "Input 5 Candidates ";
for (int i = 0; i < MAX; i++) {
cin >> candidates[i] >> votes[i];
}
printResults(candidates, votes);
cout << " winner is: " << candidates[findWinner(votes)] << endl;
return 0;
}
double calculatePercentage(int votes[], int vote){
int sumOfVotes = 0;
for (int i = 0; i < MAX; i++) {
sumOfVotes += votes[i];
}
double percentage = static_cast<double>(vote) / sumOfVotes;
return percentage*100;
}
void printResults(string candidates[], int votes[]){
cout << "Name:" << endl << "Votes:" << endl << "Percentage:" << endl;
for (int i = 0; i < MAX; i++) {
cout << candidates[i] << endl << votes[i] << endl;
int percentage = calculatePercentage(votes, votes[i]);
cout << percentage << "%" << endl;
}
}
int findWinner(int votes[]){
int winner = 0;
for (int i = 0; i < MAX; i++) {
if (votes[i] > winner)
winner = i;
}
return winner;
}
Output :
Input 5 Candidates
Lincoln
Parks
Shakespeare
Ghandi
Ashe
5000
2000
8000
2500
1750
Name:
Votes:
Percentage:
Lincoln
5000
25.97%
Parks
2000
10.38%
Shakespeare
8000
41.55%
Ghandi
2500
12.98%
Ashe
1750
9.09%
winner is: Shakespeare