EX 8.1Implementing a Menu Class
Problem StatementIn this Worked Example, our task is to write a class for displaying a menu. An object of this class can display a menu such as
1) Open new account
2) Log into existing account
3) Help
4) Quit
Reimplement the Menu class of Worked Example 8.1 so that it stores all menu items in one long string. Hint: Keep a separate counter for the number of options. When a new option is added, append the option count, the option, and a newline character.
Programming Language C++ Program which will display the list of Menu Option.
#include <iostream>
#include<string>
using namespace std;
class Menu
{
string option;
int counter;
public:
Menu()
{
counter = 0;
}
Menu(string item, int count) // parameterize constructor
{
option = option + "\n " + to_string(count) + " " + item;
}
void addOption(string item, int count) //method to add new
option
{
option = option + "\n" + to_string(count) + " " + item;
}
string display() //method to display the list of option
{
return option;
}
};
int main()
{
int counter;
string check, option;
Menu m;
m.addOption("Open new account", 1);
m.addOption("Log in to an existing account", 2);
m.addOption("Help", 3);
m.addOption("Quit", 4);
counter = 4;
cout<<m.display()<<endl; //display the list
while(true)
{
cout<<endl<<"Add more options (Yes/No): ";
cin>>check;
if(check == "Yes" || check == "yes")
{
counter++;
cout<<"What is the option name: ";
cin>>option;
m.addOption(option, counter);
}
else
{
break;
}
}
cout<<m.display(); //display the list
return 0;
}
OUTPUT:
1 Open new account
2 Log in to an existing account
3 Help
4 Quit
Add more options (Yes/No): Yes
What is the option name: Display
Add more options (Yes/No): No
1 Open new account
2 Log in to an existing account
3 Help
4 Quit
5 Display
Get Answers For Free
Most questions answered within 1 hours.