I need help with a c++ program using vectors. Below is my code
It requires me to use vectors.
This is the question:
Write a programme that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The programme should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate. Your programme should also output the winner of the election.
A sample output is:
Candidate Votes Received % of Total Votes
========= ============== ================
Johnson 5000 25.91
Miller 4000 20.73
Duffy 6000 31.09
Robinson 2500 12.95
Ashton 1800 9.33
Total 19300
I am using Code BLocks IDE,
This is my code:
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
|
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
int findWinner( vector<int> votes[]);
void printResults( vector<string> candidates[], vector <int> votes[]);
double calculatePercentage( vector<int> votes[], int vote);
const int NUMBER_OF_CANDIDATES = 5;
int main()
{
vector<string> candidates[NUMBER_OF_CANDIDATES];
vector<int> votes[NUMBER_OF_CANDIDATES];
cout << "Please input the 5 candidates followed by the votes they recieved i.e. Smith 5000: ";
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cin >> candidates[i] >> votes[i];
}
printResults(candidates, votes);
cout << "And the winner is: " << candidates[findWinner(votes)] << endl;
return 0;
}
double calculatePercentage( vector <int> votes[], int vote){
int sumOfVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
sumOfVotes += votes[i];
}
double percentage = static_cast<double>(vote) / sumOfVotes;
return percentage*100;
}
void printResults( vector<string> candidates[], vector<int> votes[]){
cout << "Name:" << setw(15) << "Votes:" << setw(15) << "Percentage:" << endl;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
cout << candidates[i] << setw(15) << votes[i] << setw(15);
int percentage = calculatePercentage(votes, votes[i]);
cout << percentage << "%" << endl;
}
}
int findWinner( vector<int> votes[]){
int winner = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
if (votes[i] > winner)
winner = i;
}
return winner;
}
|
However, there is an error on line 22 saying: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘std::vector<std::__cxx11::basic_string<char> >’)
cin >> candidates[i] >> votes[i].
I would appreciate some help. THanks