Votes received by the candidate Your program should also out
Solution
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//function to display the array data
void displayResults(string name[],int votes[],float percentages[],int size)
{
int total=0;
cout<<\"Candidate\\tVotes Received\\t% of Total Votes\ \ \";
for(int i=0;i<size;i++)
{
total+=votes[i];
cout<<name[i]<<\"\\t\\t\"<<votes[i]<<\"\\t\\t\"<<percentages[i]<<endl;
}
cout<<\"Total\\t\"<<total<<\"\\t\"<<total/size;
}
//function to detrmin winner and returns the winner name
string determineWinner(string name[],float percentages[],int size)
{
string mname=\"\";
double max=0;
//loop through array and find the one with max votes
for(int i=0;i<size;i++)
{
if(max<percentages[i])
{
max=percentages[i];
mname=name[i];
}
}
return mname;
}
//function to calculate % of votes
void calcPercents(int votes[],float percentages[],int size)
{
int total=0;
for(int i=0;i<size;i++)
{
total+=votes[i];
}
for(int i=0;i<size;i++)
{
percentages[i]=(votes[i]*100)/total;
}
}
//function which reads votes data from file and stores them into array
int inputValues(string name[],int votes[])
{
int size=0;
ifstream myfile (\"votes.txt\");
if (myfile.is_open())
{
while ( myfile>>name[size] )
{
myfile>>votes[size];
size++;
}
myfile.close();
}
else
cout << \"Unable to open file\";
return size;
}
//main function which triggers the above funcitons
int main()
{
const int size=10;
string name[size];
int votes[size];
float percentages[size];
int length=inputValues(name,votes);
calcPercents(votes,percentages,length);
displayResults(name,votes,percentages,length);
cout<<\"\ \ The Winner of the election is \"<<determineWinner(name,percentages,length)<<endl;
return 0;
}
Sample Output:
Candidate Votes Received % of Total Votes
A 5000 28
B 4000 22
C 6000 34
D 2500 14
Total 17500 4375
The Winner of the election is C

