// BallotBox.cpp. Definitions file for Ballot Box class #include #include #include #include #include "BallotBox.h" using namespace std; // // Function to read names of candidates // Pre: none // Post: Names of the candidates have been read into array names. // numCandidates is the number of candidates; // Elements 0 through numCandidates - 1 of array tally // have been initialized to zero. // void BallotBox::readCandidates() { char name[MAX_NAME_LEN]; // a candidate's name numCandidates = 0; cout << endl << endl; cout << "Enter candidate names--empty line when finished\n\n"; cout << "Enter candidate name: "; cin.getline(name, 80); while (strlen(name) > 0 && numCandidates < MAX_CANDIDATES) { strcpy(names[numCandidates], name); tally[numCandidates] = 0; numCandidates++; cout << "Enter candidate name: "; cin.getline(name, 80); } if (strlen(name) > 0 && numCandidates == MAX_CANDIDATES) { cout << "Too many candidates--program terminated\n"; exit(1); } } // // Function cast votes for candidates // Pre: The ballot box is initialized. // Post: Ballots have been cast and tallied in tally. // void BallotBox::castVotes() { int vote; // menu choice for candidate displayMenu(); cin >> vote; do { if (vote < 0 || vote > numCandidates) cout << "Invalid vote--try again\n"; else { tally[vote - 1]++; cout << "Your vote has been registered. Thank you.\n\n"; } displayMenu(); cin >> vote; } while (vote != 0); } // // Function to display election results // Pre: The ballot box is initialized and votes cast. // Post: Election results have been displayed. // void BallotBox::displayResults() { int j; // index cout << setw(30) << "Candidate" << setw(10) << "Votes\n"; for (j = 0; j < numCandidates; j++) cout << setw(30) << names[j] << setw(10) << tally[j] << endl; } // // Function to display the menu of candidates // Pre: The ballot box is initialized. // Post: The menu of candidates has been displayed. // void BallotBox::displayMenu() { int j; // index for (j = 0; j < numCandidates; j++) cout << setw(10) << j + 1 << setw(30) << names[j] << endl; cout << endl << endl << "Cast your vote (zero to end): "; }