I'm writing an electronic voting system and in the end, I want to show on the screen percentage results, not the numbers for candidates. So I collected everything in a file. It looks like this: "results.txt"
Jessica: 2
Amanda: 3
Michael: 0
Sam: 0
Alex: 1
Nancy: 0
and after that can I take these numbers to sum them and convert to a percentage? I don't know how to realize that.
This is the part of the program:
ofstream VotingResults ("results.txt", ios::app);
cout<<"Please enter a number for whom you give your vote: ";
cin >> choice;
switch (choice)
{
case 1:
Vote(Jessica);
cout<<"Press any button to get the results";
break;
case 2:
Vote(Amanda);
cout<<"Press any button to get the results";
break;
case 3:
Vote(Michael);
cout<<"Press any button to get the results";
break;
case 4:
Vote(Sam);
cout<<"Press any button to get the results";
break;
case 5:
Vote(Alex);
cout<<"Press any button to get the results";
break;
case 6:
Vote(Nancy);
cout<<"Press any button to get the results";
break;
default:
cout<<"Invalid number! Press any button to get the results";
break;
}
VotingResults.open("results.txt");
VotingResults << "Jessica: " << Jessica << endl
<< "Amanda: " << Amanda << endl
<< "Michael: " << Michael << endl
<< "Sam: " << Sam << endl
<< "Alex: " << Alex << endl
<< "Nancy: " << Nancy << endl;
VotingResults.close();
void Vote(int &a)
{
a += 1;
cout << "\n\t\tThank you for your vote! ";
}
I recommend using
std::mapfor this:If the name exists in the map, the value field is incremented. The value field will represent the number of votes (or occurrences).
The number associated with the voter is read, but not used, in order to keep the reading synchronized.