Well, line 17 won't work:
|
double percentage[5] = {votes[5] / total};
|
When that line is executed, total is zero, so there's a divide by zero error there. Best just to initialise that array with zero, like the votes.
The program seems constructed on the assumption that there will be exactly 5 lines of data in the input file, no more and no less. In my opinion, the program should be more flexible, perhaps allow for say 10 or even 20 candidates, and make the arrays big enough to store that many rows of data.
Then in function getData() you could count how many rows of data are actually read from the file. Well actually you are already doing that, the variable
i
acts as a count, but you don't do anything with that information. You might change function DisplayData() to accept an additional parameter, the count of the number of rows of data in the arrays.
But first there are two issues to deal with. We'll come to the percentages in a moment. There's another problem before we do that.
At line 34
while (!in.eof())
this while condition is not a good idea. Why, because it checks the condition of the input file
before reading from it. What the program really needs to know is this: when the line
in >> name[i] >> votes[i];
is executed, does it fail or succeed? You can only answer this question by testing the file
after executing that line.
So, I recommend changing that code like this:
33 34 35 36 37 38
|
int i = 0;
while (in >> name[i] >> votes[i])
{
total = total + votes[i];
i++;
}
|
After that, as I said, we can use the value of
i
to tell us how many rows of data were read from the file. Now we get to calculate the percentages, like this:
1 2 3 4
|
for (int k=0; k<i; k++)
{
percentage[k] = // here calculate percent from votes and total
}
|
And as i suggested, modify the
DisplayData()
function to accept one more parameter
|
void DisplayData(ofstream &out, string name[], int votes[], double percentage[], int total, int numRows)
|
and call it like this:
|
DisplayData(out, name, votes, percentage, total, i);
|
and of course use the new parameter at line 51,
|
for (int i = 0; i < numRows; i++)
|