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
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
bool readFile(string[], int *);
void calculatePercents(int v[], double p[], int);
void displayResults(string c[], int v[], double p[], int);
void getVotes(int v[], int);
int main()
{
int n = 25;
string c[n];
int v[n];
double p[n];
getVotes(v, n);
readFile(c, &n); //calling function to read candiadtes names from files
calculatePercents(v, p, n);//to get votes using random number genertor and to calculate percentage of votes for each candidate
displayResults(c, v, p, n);//calling function to display results
}
void getVotes(int v[], int size)
{
int min = 1500;
int max = 25000;
for (int i = 0; i<size; i++)
{
v[i] = (int)min + (rand() % (max - min + 1));//random number generator between 1500 and 25000
}
}
void displayResults(string c[], int v[], double p[], int size)
{
cout << "\nCandidates Votes \tPercent\n";
int max = v[0];//to hold max number of votes
int pos = 0;//which position in array has max number of votes which will be usefull to declare the winner
for (int i = 0; i<size; i++)
{
if (max<v[i])
{
max = v[i];
pos = i;
}
cout << "\n" << c[i];
cout << "\t " << v[i] << "\t" << std::setprecision(2) << p[i] << "%";
}
cout << "\n Winner is " << c[pos] << " with " << v[pos] << " Votes";
}
void calculatePercents(int v[], double p[], int n)
{
int sum = 0;//to hold sum of all candidates votes
int min = 1500;
int max = 25000;
for (int i = 0; i<n; i++)
{
v[i]=(int) min + ( rand() % ( max - min + 1 ) );//random number generator between 1500 and 25000
sum += v[i];
}
for (int i = 0; i<n; i++)
{
p[i] = ((double)v[i] / (double)sum) * 100;//calculating percentage of votes fro each candidate
}
}
bool readFile(string c[], int *size)
{
string candidate;
ifstream in;
in.open("candidates.txt");//opening file
int i = 0;
while(i<*size)
while (in >> candidate)//reading till end of file
{
cout << candidate;
c[i] = candidate;//assigning to array of candidate names
i++;
}
*size = i;//assinging size of array
}
|