Hi guys, the question I am attempting is below
A program is required to register user votes for a number of talent contest candidates. When all the votes have been cast, the program should sort the candidates into order, based on the number of votes they have received and output them to the screen.
Create a Candidate class to represent the candidate, storing their name and the number of votes they receive (initially 0). The class should provide methods to get and set the name, increment the votes by 1, and get the number of votes.
The voting program should prompt the user to enter the number of candidates, followed by that number of candidate names.
The program then prompts the user to repeatedly enter the names of the candidates; each input of a name is a vote and the program increments the number of votes for that candidate by 1.
When all voting has finished, the user should enter "end" and the program should sort the Candidate objects into descending order of number of votes and output the results.
Code:
/*#include "Header.h"
#include <iostream>
#include <string>
using namespace std;
//Task 2 Votes
#include "candidates.h"
#include "Header.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0, j = 0;
cout << "Enter the number of candidates: ";
cin >> num;
cin.ignore();
candidates* c = new candidates[num];
readNames(c, num, j);
vote(c, num);
sort(c, num);
print(c, num);
delete[] c;
system("PAUSE");
return 0;
}
void readNames(candidates c[], int num, int j)
{
string Cname;
for (int i = 0; i < num; i++)
{
j++;
cout << "\nEnter the name of Candidate no. " << j << ": ";
getline(cin, Cname);
c[i].setName(Cname);
cout << endl;
}
}
void vote(candidates c[], int num)
{
string vote;
cout << "\nType <end> to close the program";
do
{
cout << "\nEnter the name of the candidate you woulld like to vote for: ";
getline(cin, vote);
for (int j = 0; j < num; j++)
{
if (vote == c[j].getName())
{
c[j].incrementVotes();
}
}
} while (vote != "end");
}
void sort(candidates c[], int num)
{
int j = 0;
bool swap = true;
candidates temp;
while (swap)
{
swap = false;
j++;
for (int l = 0; l < num - j; l++)
{
if (c[l].getVotes() > c[l + 1].getVotes())
{
temp = c[l].getName();
c[l].getName() = c[l + 1].getName();
c[l + 1].getName() = temp;
swap = true;
}
}
}
}
void print(candidates c[], int num)
{
for (int k = 0; k < num; k++)
{
cout << "\nno. of votes for " << c[k].getName() << ": " << c[k].incrementVotes() << endl;
}
}
Code:
#include "candidates.h"
candidates::candidates()
{
noOfvotes = 0;
}
candidates::~candidates()
{
}
void candidates::setName(string n)
{
name = n;
}
string candidates::getName()
{
return name;
}
int candidates::getVotes()
{
return noOfvotes;
}
int candidates::incrementVotes()
{
return noOfvotes++;
}
I am having trouble with the sort function, I want to output the results by number of votes. I am having alot of trouble with this....any help would be greatly appreciated