1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
int sumList(const int[], int);
int indexOfMax(const int[], int);
void getElectionData(ifstream&, string[], int[], int& );
void printResults(const string[], const int[], int, int);
const int NUM_CANDIDATES = 10;
int main()
{
ifstream inFile;
string names[NUM_CANDIDATES];
int votes[NUM_CANDIDATES];
int totalVotes;
int max;
inFile.open("votingresults.txt");
if (!inFile)
{
cout << "File not found!" << endl << endl;
system("pause");
return 1;
}
getElectionData(inFile, names, votes, max);
totalVotes = sumList(votes ,max);
printResults(names, votes, max, totalVotes);
inFile.close();
cout << max << endl << endl;
return 0;
}
int sumList(const int list[], int size)
{
int i, sum = 0;
for(i = 0; i<size; i++)
{
sum = list[i] + sum;
}
return sum;
}
int indexOfMax(const int list[], int size)
{
int i = 0;
int maxIndex = 0;
int maxValue = 0;
for(; i < size; i++)
{
if(list[i] > maxValue)
{
maxValue = list[i];
maxIndex = i;
}
}
return maxIndex;
}
void getElectionData(ifstream & iFile, string candidates[], int ballots[], int & count)
{
int i = 0;
while(iFile >> candidates[i] >> ballots[i])
{
i++;
}
count = i;
}
void printResults(const string candidates[], const int ballots[], int count, int totalBallots)
{
int i = 0;
int winner;
cout << setw(15) << "Candidates" << setw(20) << "Num Votes" << setw(20) << "% of votes" << endl << endl;
for(; i < 6; i++)
{
cout << setw(15) << candidates[i] << setw(20) << ballots[i] << setw(20) << totalBallots/count << endl;
}
winner = indexOfMax(ballots, count);
cout << "The winner is: " << candidates[winner] << endl;
}
|