I'm trying to learn how to create a menu, i got this code online, and have been tweaking it, however i'm not sure how i can add more options to it, any hints would be helpful.
Before idly using any random piece of code off the internet (or other sources) you should analyse it and understand what each little piece is doing and why.
I'll give you a hand with 2 pieces which are less common but the rest is just C++ and you should be able to see what needs to be done to add options as long as you look to try and find what bits of code are doing what.
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD);
If I can remember correctly this rather large line simply changes the colour of the text (it certainly changes the format in one way or another) in your console when outputting data via the std output handle (this handle is used in printf and cout). So now you can rule that out of anything to do with adding options.
GetAsyncKeyState(int)
This checks (asynchronously) if a key is currently pressed by simply returning true or false. Now this is used to test for VK_UP, VK_DOWN and VK_RETURN in your code. So add a new menu option may have something to do with the selection of an option (which is done with VK_RETURN)
Take a look at the rest of the code and analyse it to find out how it works, this is a skill you'll need to become a good programmer.
At line 7 you define MainMenu to be an array of 4 items, but only provide 3 values in the initializer.
At lines 18-31 you proceed to cout 4 items. The fourth item is going to be garbage,if it doesn't crash your program.
You didn't clearly state your objectives, so it's unclear how simple or complex a menu system you want. Is varying text color a requirement? If not you can get rid of that. Traditional text oriented menus in C++ are a lot simpler and don't require checking asynchronous key state.
1 2 3 4 5 6 7 8 9 10 11 12 13
// Display menu options
int choice;
do
{ cout << "Enter choice: ";
cin >> choice;
}
while (! (choice >= 1 && choice <= num_choices));
switch (choice)
{
case 1: function1 (); break;
case 2: function2 (); break;
// etc
}
More complex menu systems can involve a class dedicated to menu handling that can handle a variable number of menu items. This might give you an idea of where to start:
1 2 3 4 5 6 7 8 9 10
struct menuitem
{ void (*func)(); // function pointer to handler for option
string optionname;
};
class Menu
{ vector<menuitem> m_menuitems;
public:
void AddMenuItem (void (*func)(), string optname);
void DisplayMenu ();
};
@xvvll Hey I don't mind helping people and responding to questions but please don't send messages about a topic that's got a thread created for it, especially when you've created the thread yourself and it'd actually be more beneficial to post your response into the thread for others to see so they can help you further.