Help Queue
Problem
You have been hired to TA this fall
You want to build a help queue where students can help each other! Thus, the program needs to be able to add and remove a student one at a time. The queue should allow multi-word names.
Your program has two options:
Ask for help
Help a student
Solution
/*
Test case 1
Input: option 1
Output: prompt for name, adds name when given
Test case 2
Input: option 2 (with empty queue)
Output: Nothing is removed from queue
Test case 3
Input: option 2 (nonempty queue)
Output: Name in first position is removed
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int ASK_HELP_OPT = 1;
const int GIVE_HELP_OPT = 2;
/*
Display the queue to the console
@param queue queue to display
*/
void display_queue(const vector<string> & queue)
{
cout << "CURRENT QUEUE:" << endl;
for (int i = 0; i < queue.size(); i++)
{
// print out 1-based, labeled list of names who are waiting
cout << (i + 1) << ". " << queue[i] << endl;
}
}
/*
Shows menu and gets user's menu choice. No input validation
@return user's menu choice
*/
int prompt_for_option()
{
cout << "*************MENU***************" << endl
<< ASK_HELP_OPT << ". Ask for help" << endl
<< GIVE_HELP_OPT << ". Give help" << endl
<< "Option: ";
int option;
cin >> option;
cout << endl;
return option;
}
/*
Function checks if queue is non-empty and then removes next to be helped from the queue
@param queue the queue of those waiting for help
*/
void give_help(vector<string> & queue)
{
if (queue.size() == 0)
{
return;
}
else
{
// Take out first person
string name_of_being_helped = queue[0];
// Move everyone else up
// alternative: queue.erase(queue.begin());
for (int i = 0; i < queue.size() - 1; i++)
{
queue[i] = queue[i + 1];
}
queue.pop_back(); // reduce the size of the array
}
}
/*
Function prompts for name of person needing help, then adds it to the queue
@param queue queue of those waiting to be helped
*/
void ask_help(vector<string> & queue)
{
cout << "Name to add:";
string name;
// Have to sync in case there's a \n character waiting in the cin buffer from cin>>option
cin.sync();
getline(cin, name); // this allows us to get names with multiple words
queue.push_back(name);
}
int main()
{
vector<string> help_queue;
while (true)
{
// display the queue
display_queue(help_queue);
// prompt for an option
int option = prompt_for_option();
// either add to the queue or remove from the queue
if (option == ASK_HELP_OPT)
{
ask_help(help_queue);
}
else if (option == GIVE_HELP_OPT)
{
give_help(help_queue);
}
}
system("pause");
return 0;
}
Back to top