In: Computer Science
C++
Write a program that reads candidate names and numbers of votes in from a file. You may assume that each candidate has a single word first name and a single word last name (although you do not have to make this assumption). Your program should read the candidates and the number of votes received into one or more dynamically allocated arrays.
In order to allocate the arrays you will need to know the number of records in the file. In order to determine the number of records in the file you may include the number as metadata in the first line of the file or you may read through the file to count the lines and then reset the file pointer back to the beginning of the file to read in the data. Do not hard code the number of candidates. Do not prompt the user to enter the number of candidates. You must either count the number of candidates in the file or encode the number as metadata as the first record in the file.
The program should output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. You may, but are not required to, use the example file provided.
C++ Program:
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
const int no0fcandidate = 100;
int main()
{
int cnt;
string cNames[no0fcandidate];
string cLNames[no0fcandidate];
int votes[no0fcandidate];
float voteP[no0fcandidate];
int totalVotes = 0;
float maxVotesPercentage;
string winner;
//Opening file for reading
fstream fin("votes.txt", ios::in);
//Reading number of contestants
fin >> cnt;
for (int i = 0; i < cnt; i++)
{
fin >> cNames[i] >> cLNames[i] >> votes[i];
}
//Calculating total number of votes
for (int i = 0; i < cnt; i++)
{
totalVotes = totalVotes + votes[i];
}
//Finding average
for (int i = 0; i < cnt; i++)
{
voteP[i] = ((float) votes[i] / totalVotes) * 100;
}
//Percentage
maxVotesPercentage = voteP[0];
//Winner
winner = cNames[0];
//Calculating winner
for (int i = 0; i < cnt; i++)
{
//Comparing
if (voteP[i] > maxVotesPercentage)
{
maxVotesPercentage = voteP[i];
winner = cNames[i];
}
}
//Printing result
cout << endl << left << setw(15) << " "
<< left << setw(25) << "Candidate " << left
<< setw(20) << "Votes Received" << left <<
setw(15) << "% of Total Votes" << endl <<
endl;
cout << fixed << setprecision(2);
for (int i = 0; i < cnt; i++)
{
cout << left << setw(6) << " " << left
<< setw(20) << cNames[i] << left <<
setw(20) << cLNames[i] << left << setw(20)
<< votes[i] << left << setw(15) << voteP[i]
<< endl;
}
cout << endl << left << setw(6) << " " << left << setw(20) << "Total " << left << setw(20) << totalVotes << endl;
cout << endl << "The Winner of the Election is "
<< winner << endl;
return 0;
}
_________________________________________________________________________________________
Sample Run: