Question

Write a int function that accepts as parameter the name of a candidate and return the...

Write a int function that accepts as parameter the name of a candidate and return the number of votes received by the candidate. So, if the user enters Duck, the output will be 6000. Of course, if the given name does not exist, display an appropriate message.

Need help with the above here is what i have so far:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <map>

using namespace std;

// Get the details from the user for the candidates
void askdetails(vector<string>& name, vector<int>& vote)
// The vector is passed by reference
{
   string s;
   int v;
   while (true)
   {
       cout << "Give name of contestant (press # and enter to exit)";
       cin >> s;
       if (s == "#") break;
       name.push_back(s);
       cout << "Enter no of votes for " << s << endl;
       cin >> v;
       vote.push_back(v);
   }
}


// Get the winner of the vote and return name
string winner(const vector<string>& name, const vector<int>& vote)
{
   string s;
   int i, in = 0, m = 0;
   for (i = 0; i < vote.size(); i++)
       if (vote[i] > m)
       {
           m = vote[i];
           in = i;
       }
   cout << "\nThe winner of the election is " << name[in] << " with " << vote[
       in] << " votes" << endl;
   return name[in];
}

// Get the loser of the vote and return name
string loser(const vector<string>& name, const vector<int>& vote)
{
   string s;
   int i, in = 0, m = INT_MAX;
   for (i = 0; i < vote.size(); i++)
       if (vote[i] < m)
       {
           m = vote[i];
           in = i;
       }
   cout << "The loser of the election is " << name[in] << " with " << vote[in]
       << " votes" << endl;
   return name[in];
}

//Calculate the average number of votes
int averagevotes(const vector<int>& vote)
{
   int i, s = 0;
   for (i = 0; i < vote.size(); i++)
       s += vote[i];
   cout << "\nAverage votes\t" << s / vote.size() << endl;
   return s / vote.size();
}

// Claculate the total number of votes
int totalvotes(const vector<int>& vote)
{
   int i, s = 0;
   for (i = 0; i < vote.size(); i++)
       s += vote[i];

   cout << "\nTotal\t\t" << s << endl;
   return s;
}

// Sort the out put by number of votes
void sortname(const vector<string>& name, const vector<int>& vote,
map<string, int>& m) // The vector is passed by reference
{
   int i;
   for (i = 0; i < vote.size(); i++)
       m[name[i]] = vote[i];
}

void display(map<string, int> m, const vector<int> vote)
{
   // Output the summary header
   cout << "\nCandidate" << "\t" << "Votes Recieved" << "\t" <<
       "% of Total votes" << endl;

   map<string, int>::iterator it;
   int i, s = 0;
   for (i = 0; i < vote.size(); i++)
       s += vote[i];
   for (it = m.begin(); it != m.end(); ++it)
   {
       // output vote details in the table
       cout << endl;
       cout << it->first << "\t\t" << it->second << "\t\t";
       printf("%.2f", ((float)it->second / (float)s) * 100);
       cout << endl;
   }
}


int main()
{
   // delcare variables
   vector<int> vote;
   vector<string> name;
   map<string, int> m;

   // get the user input
   askdetails(name, vote);

   //sort and display the candidate information
   sortname(name, vote, m);
   display(m, vote);

   // calculate the total votes and the average votes
   totalvotes(vote);
   averagevotes(vote);

   // output the winner and loser details
   winner(name, vote);
   loser(name, vote);


   return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

So far you've made a map of the candidate names and their corresponding votes. We'll use this same map to search for the candidate name and query the no. of votes from this map only.

First, we define the function that counts the votes:

//START FUNCTION 1
int count_votes(string name,map<string, int> m){ //Pass the name of candidate and the map
if ( m.find(name) == m.end() ) { //means the name is not found

return -1; // returning -1 to indicate error
} else {
return m.at(name); // return value at the key "name"
}
}

//END FUNCTION 1

Second, we define the function that acts as an interface with the user:

//START FUNCTION 2
void display_count(map<string,int>m){ //display the vote count of desired candidates, takes in the map of name and votes
string name; //This string is used to query the map.
while(true){
cout<<"Enter the name of candidate (Enter # and enter to exit):";
cin>>name; //Taking user input for the desired candidate
if(name=="#") //If user inputs #
break; //break loop and return

//find the no. of votes of "name" from the map "m" by invoking the count_votes function
int votes = count_votes(name,m);
if (votes == -1)
cout<<"Error: Candidate does not exist!"<<endl; //print error message in case Candidate not found
else
cout<<"No. of votes of "<<name<<" is: "<<votes<<"."<<endl; //print no. of votes
}

return 0;
}

//END FUNCTION 2

Third, we call the display_count funtion in our main function:

display_count(m); //operate on map "m"

Add a comment
Know the answer?
Add Answer to:
Write a int function that accepts as parameter the name of a candidate and return the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program that supports the three phases (setup, voting and result-tallying) which sets up and...

    Write a program that supports the three phases (setup, voting and result-tallying) which sets up and executes a voting procedure as described above. In more details: You can start with the given skeleton (lab6_skeleton.cpp). There are two structures: Participant structure, which has the following members: id -- an integer variable storing a unique id of the participant (either a candidate or a voter). name -- a Cstring for storing the name of the participant.. hasVoted -- a boolean variable for...

  • I need to add something to this C++ program.Additionally I want it to remove 10 words...

    I need to add something to this C++ program.Additionally I want it to remove 10 words from the printing list (Ancient,Europe,Asia,America,North,South,West ,East,Arctica,Greenland) #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int> words);    int main() { // Declaring variables std::map<std::string,int> words;       //defines an input stream for the data file ifstream dataIn;    string infile; cout<<"Please enter a File Name :"; cin>>infile; readFile(infile,words);...

  • I need to make a few changes to this C++ program,first of all it should read...

    I need to make a few changes to this C++ program,first of all it should read the file from the computer without asking the user for the name of it.The name of the file is MichaelJordan.dat, second of all it should print ,3 highest frequencies are: 3 words that occure the most.everything else is good. #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int>...

  • CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer;...

    CODES: main.cpp #include <iostream> #include <string> #include "ShoppingCart.h" using namespace std; char PrintMenu() { char answer; cout << "MENU" << endl; cout << "a - Add item to cart" << endl; cout << "d - Remove item from cart" << endl; cout << "c - Change item quantity" << endl; cout << "i - Output items' descriptions" << endl; cout << "o - Output shopping cart" << endl; cout << "q - Quit" << endl << endl; while (true) {...

  • Use main.cpp, Student.h, Student.cpp (written below) and write classes StudentClub and a non-member function find youngest...

    Use main.cpp, Student.h, Student.cpp (written below) and write classes StudentClub and a non-member function find youngest to make main.cpp compile. Put the declaration and definition of find youngest in StudentClub.h and StudentClub.cpp separately. You may not modify provided files and only submit StudentClub.h and StudentClub.cpp. Non-member function find youngest is declared as follows. It returns the names of students who have the youngest age. Note there may exist more than one students who are youngest. std::vector find_youngest(const std::vector member); StudentClub...

  • Coding in c++

    I keep getting errors and i am so confused can someone please help and show the input and output ive tried so many times cant seem to get it. main.cpp #include <iostream> #include <vector> #include <string> #include "functions.h" int main() {    char option;    vector<movie> movies;     while (true)     {         printMenu();         cin >> option;         cin.ignore();         switch (option)         {            case 'A':            {                string nm;                int year;                string genre;                cout << "Movie Name: ";                getline(cin, nm);                cout << "Year: ";                cin >> year;                cout << "Genre: ";                cin >> genre;                               //call you addMovie() here                addMovie(nm, year, genre, &movies);                cout << "Added " << nm << " to the catalog" << endl;                break;            }            case 'R':            {                   string mn;                cout << "Movie Name:";                getline(cin, mn);                bool found;                //call you removeMovie() here                found = removeMovie(mn, &movies);                if (found == false)                    cout << "Cannot find " << mn << endl;                else                    cout << "Removed " << mn << " from catalog" << endl;                break;            }            case 'O':            {                string mn;                cout << "Movie Name: ";                getline(cin, mn);                cout << endl;                //call you movieInfo function here                movieInfo(mn, movies);                break;            }            case 'C':            {                cout << "There are " << movies.size() << " movies in the catalog" << endl;                 // Call the printCatalog function here                 printCatalog(movies);                break;            }            case 'F':            {                string inputFile;                bool isOpen;                cin >> inputFile;                cout << "Reading catalog info from " << inputFile << endl;                //call you readFromFile() in here                isOpen = readFile(inputFile, &movies);                if (isOpen == false)                    cout << "File not found" << endl;...

  • 10.18 LAB: Plant information (vector) Given a base Plant class and a derived Flower class, complete...

    10.18 LAB: Plant information (vector) Given a base Plant class and a derived Flower class, complete main() to create a vector called myGarden. The vector should be able to store objects that belong to the Plant class or the Flower class. Create a function called PrintVector(), that uses the PrintInfo() functions defined in the respective classes and prints each element in myGarden. The program should read plants or flowers from input (ending with -1), adding each Plant or Flower to...

  • Please help fix my code C++, I get 2 errors when running. The code should be...

    Please help fix my code C++, I get 2 errors when running. The code should be able to open this file: labdata.txt Pallet PAG PAG45982IB 737 4978 OAK Container AYF AYF23409AA 737 2209 LAS Container AAA AAA89023DL 737 5932 DFW Here is my code: #include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdlib> #include <iomanip> using namespace std; const int MAXLOAD737 = 46000; const int MAXLOAD767 = 116000; class Cargo { protected: string uldtype; string abbreviation; string uldid; int...

  • I need help with this assignment, can someone HELP ? This is the assignment: Online shopping...

    I need help with this assignment, can someone HELP ? This is the assignment: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by...

  • Who could write the array.cpp file ?   //main.cpp #include "array.hpp" #include <iostream> int main() { int...

    Who could write the array.cpp file ?   //main.cpp #include "array.hpp" #include <iostream> int main() { int n; std::cin >> n; array a(n); for (int i = 0; i < n; i++) { std::cin >> a.data()[i]; } std::cout << "array size:" << a.max_size() << std::endl; std::cout << "array front:" << a.front() << std::endl; std::cout << "array back:" << a.back() << std::endl; int* data = a.data(); std::cout << "array elements using data:" << std::endl; for (int i = 0; i < n;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT