How to alternate from one function to another - c++

I have these functions:
read(){
}
write(){
}
main(){
cout << "This is a menu so you can choose what to do";
}
Its actualy more complicated than that but that example will do fine for you to help me.
I just want to be able to for example write, then go back to the menu, then choose to read etc
I cant do :
read(){
main();
}
main(){
read();
}
because main was not declared before read, so then I move main above read and read was not declared before main.
Exactly this program is an agenda, so that I can creat schedules and manage events (write) and just see my calendar with all the events or just see my schedules (read). I want to be able to go from main to read, then to main again then to write you know
I think I could separate these functions into different files but I dont know how to call a function from another file.
Any help?

Here's another alternative:
int main(void)
{
bool call_read = true;
while (true)
{
if (call_read)
{
read();
}
else
{
write();
}
call_read = !call_read;
}
return 0;
}
In the above example, a bool variable is used to alternate between the read and write functions.
A nice feature of this method is that the functions called don't need to know about each other.

ok, calling main is not a good idea, but I guess the question is more about how having 2 functions calling each other.
you need to forward declare at least one:
int write(); //forward declare
int read() {
return write(); // use write which is still forward declared for now
}
int write() { // now defining write
return read();
}
obviously this sample code is meaning less (infinite loop), but it illustrates how to do that.

A good way to write menus is to use a while loop in main and a switch statement. Assuming the read and write functions do not branch somewhere else, when they complete, they return to their caller, main(). The while loop ensures that the menu does not end until the user is done.
int main()
{
char choice = '\n';
while (choice != 'q')
{
// Display menu options
cout << "r: Read" << endl << "w: Write" << endl << "Enter a choice: ";
cin >> choice;
// Implement menu interface
switch (choice)
{
case 'r':
read();
break;
case 'w':
write();
break;
case 'q':
cout << "Quitting the menu. Bye!" << endl;
break;
default:
cout << "Invalid choice!" << endl;
break;
} //end switch
} // end while
return 0;
} // end main

Related

Big problem with classes , and returning from void function c++

so that's my first time learning a language , and I was really excited to play with classes, i do have one major problem which i cant seem to understand ;
im building a bank menu . its a class ofcourse, and i have a different class of clients which is basicly an array in my bank.
so my menu function inside the bank looks like that :
void menu (){
manager();
int n,m;
cout << "welcome to our bank managment system. \n";
cout << "please choose one of the following options : \n";
cout << "1-add a new client\n";
cout << "2-remove a leaving client\n";
cout << "3-bank statistics\n";
cout << "4-if you are a costumer\n";
cout << "5-exit\n";
cin >> n ;
if()
if()
if()
if()
if()
note that my return function is been summoned a lot inside
i have a return function to go back to the menu :
void returnfunction (){
int back = 0;
cout << "\n0-back to menu \n press a diffrent number back to exit :)\n";
cin >> back ;
if (back==0){
return menu();
}
if (back!=0){
cout << "thank you for using our program ! ";
return ;
}
it is working perfect until i play with it to much , and then hit 5 to exit (that's my option for n==5)
i must emphasize that when im hitting 5 only after few simple actions its working fine...
how can i fix that return function ?
ofcourse my main looks like that :
int main()
{
srand (time(NULL));
Bank b ;
b.menu();
}
appricate all of your wisom , thanks a lot
Your function:
void returnfunction ()
is declared to return nothing (void) but you:
return menu();
do return something, that's very unclear (even though menu() returns void too)
If you want to call menu() and then return write:
menu();
return;
There are a couple problems with this code, and honestly it wouldn't compile in other imperative OO languages. But this is c++ where the rules don't matter. Aside: If you don't have a strong reason to be using C++, learn Rust first. I promise you'll thank me later.
Paul has the right of it. The compiler should error out at that statement:
return menu();
However the equivalent is perfectly legal:
menu();
return;
But this still will cause problems in theory (but maybe not in practice) because your function is almost, but not, a candidate for tail recursion optimisation. More here Which, if any, C++ compilers do tail-recursion optimization?
This becomes a problem when users return to the menu many times, it depletes your programs memory, eventually leading to a stack overflow fault. The common pattern you'll find in most every GUI / Graphics library is that of a main-loop. Something like:
int main() {
bool exit = false
while(!exit) {
int action = menu()
switch(action) {
case EXIT_SELECTION: exit = true; break;
case SHOW_STATISTICS: printStats(); break;
}
}
}
Each time you call a function, your program has to use more memory to keep track of everything related to that function call. Ordinarily this memory is released once a function ends, but because your menu function calls another function that calls your menu function that calls another function... and on and on, you will eventually run out of memory from all of the function calls since these functions cannot terminate until the functions they call terminates -- and thus your program will crash. The solution is to use a while loop and check the user's input for an exit code as a previous responder mentioned. It can look something like:
`void menu() {
char choice= '\0';
while(choice!= 3) {
std::cout << "Welcome to the menu!";
std::cout << "\t Option 1 \n";
std::cout << "\t Option 2 \n";
std::cout << "\t Option 3 \n";
std::cout << "Your option: ";
std::cin >> choice;
if(choice == 1) { /*do something*/ }
else if(choice == 2) { /*do something else*/ }
else if(choice == 3) { /*print a message and exit*/ }
else { /*bad choice -- try again*/ }
} //end while-loop
} //end menu()`
Also, notice that your functions' return types are void, which, by definition, cannot have any sort of return. C++ will allow you to say return; inside of a void function, but it is merely a way to escape the function right then and there and is not really intended to do anything more than that. Using return in any other way when working with void functions is confusing and runs a risk of causing big issues.

loop not working?

After the call for Back to Main Menu, it returns to the mainMenu but when option or command is typed, the option is not accepted or the loop not working. Wonder where is the mistake? Is it extra call should be added or?
#include <iostream>
using namespace std;
char mainMenu(void);
int factorial(int n);
unsigned long long combination(long nK, long nR);
int main(){
char option;
int shape,function,i,j,k,t,n;
long nK, nR;
unsigned long long COM;
while((option=mainMenu())!='0')
{
switch(option)
{
case '1'://Program 1:
cout<< "*Drawing a shape\n"
<< "(1-Rectangle, 2-Triangle, 3-Inverted Triangle, 4-Letter 'H', 0-Back to Main Menu)\n";
do
{
cout<< "Choose shape >> ";
cin>> shape;
cout<< endl;
switch(shape)
{
case 1: break;
case 2: break;
case 3: break;
case 4: break;
case 0:
//Back to Main Menu
cout<< "Back to main menu\n"
<< endl;
return mainMenu(); //After here, it does back to Main Menu but command or option is not working
}
}while(shape!=0);
case '2': //Program 2
cout<< "*Choose function of calculator\n"
<< "(1-Factorial, 2-Combination, 0-Back to main menu)\n";
do
{
cout<< "Choose function >> ";
cin>> function;
cout<< endl;
switch(function)
{
case 1: break;
case 2: break;
case 0:
cout<< "Back to main menu\n"
<< endl;
return mainMenu();
}
}while(function!=0);
case '0':
cout<< "Program is terminating\n"
<< endl;
return 0;
default:
cout<< "Wrong input. Please choose one of the above options.\n"
<< endl;
return mainMenu();
}
}
}
char mainMenu(void){
char option;
cout<< "##############################\n"
<< "Main Menu\n"
<< "Enter your command!\n"
<< "##############################\n"
<< endl
<< "1. Program1\n"
<< "2. Program2\n"
<< "0. Exit\n"
<< endl
<< "Command >> ";
cin>> option;
cout<< endl;
return option;
}
I'm not sure what your question is, but your code is missing 2 important things. First, you need break statements at the end of each case block, otherwise the program flow will continue on to the next case statement.
Second, the inner menu doesn't ever escape the inner while(1) loop. This is a possible case for a goto use, although in practice it would better to refactor the code to split the top menu and inner menu into two functions, and use a return in the inner menu to return to the outer menu.
I'm not sure what your question is, but your code is missing 2 important things. First, you need break statements at the end of each case block, otherwise the program flow will continue on to the next case statement.
Second, the inner menu doesn't ever escape the inner while(1) loop. This is a possible case for a goto use, although in practice it would better to refactor the code to split the top menu and inner menu into two functions, and use a return in the inner menu to return to the outer menu.
As said, you're code is missing various things. It would be awesome if you distribute the entire code, and additionally the exact error message with line.
void value not ignored as it ought to be?...
...Is not that much of an explanation...
Also, are you sure you included iostream?
#include iostream
That said, you did not declare any of the variables used in the program.
You also missed a space in line 2 of your mainMenu() function.
Also, please tell us what you expected to happen.

Navigating console menu

I'm totally new and I don't know how else to ask this or what to even search for.
The case is this: I want to navigate through a menu with several sub-menus. In this example I'll just use "options" and a "game" to illustrate what I mean. Say you have a menu with 3 options.
1 - Start
2 - Options
3 - Quit
Choosing options should take you to another menu. Which would then look something like
1 - Difficulty
2 - Sound
3 - Back
Depending on where you go from here, there will be more sub menus obviously.
I've tried nesting do-while loops and all kinds of things but I just don't have enough understanding to know what it is I'm doing wrong.
Here is what I have so far:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int choice;
do{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
cout <<"????\n";
break;
case 3:
cout << "Goodbye!";
break;
default:
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
}
} while(choice !=3);
system("PAUSE");
return EXIT_SUCCESS;
}
Which works like a regular menu. But I have no idea where to go from here. I consulted some books, but finding anything even remotely related to this was completely random. Any help or examples would be greatly appreciated.
What happened with nesting tons of loops just made all loops execute simultaneously every time. How do I keep this from happening? Making more choices? (choice1-2-3 etc ? or what?)
Ok guys. Thanks for all the help. This is what I ended up with in the end.
It runs as I want it to and by max_'s example and Mike B's commentary I think this works pretty well.
Thanks alot everyone =)
#include <iostream>
#include <cstdlib>
using namespace std;
void menu();
void mainMenu();
void optionsMenu();
void options();
int choice1 = 0;
int choice2 = 3;
int main(int argc, char** argv) {
menu();
return 0;
}
void menu(){
do {
choice2 = 0;
mainMenu();
switch(choice1) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
options();
break;
case 3:
break;
}
} while(choice1 != 3);
}
void options(void) {
do {
optionsMenu();
switch(choice2){
case 1:
cout << "So difficult!\n";
break;
case 2:
cout << "Beep!\n";
break;
case 3:
break;
default:
break;
}
} while(choice2 != 3);
}
void mainMenu(void) {
cout << "Main Menu\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Please choose: ";
cin >> choice1;
}
void optionsMenu(void) {
cout << "Options Menu\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound";
cout << "3 - Back\n";
cout << "Please choose: ";
cin >> choice2;
}
How about this (dunno if it compiles though):
#include <cstdlib>
#include <iostream>
using namespace std;
int GetInput()
{
int choice;
cin >> choice;
return choice;
}
void DisplayMainMenu()
{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
}
void DisplayOptionsMenu()
{
cout << "Options Menu\n";
cout << "Please make your selection\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound\n";
cout << "3 - Back\n";
cout << "Selection: ";
}
void Options()
{
int choice = 0;
do
{
system("cls");
DisplayOptionsMenu();
choice = GetInput();
switch(choice)
{
case 1:
cout << "difficulty stuff";
break;
case 2:
cout << "sound stuff";
break;
case 3:
break;
default:
break;
}
} while(choice!=3);
}
int main(int argc, char *argv[])
{
int choice = 0;
do
{
system("cls");
DisplayMainMenu();
choice = GetInput();
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
Options();
break;
case 3:
cout << "Goodbye!";
break;
default:
break;
}
} while(choice!=3);
system("PAUSE");
return EXIT_SUCCESS;
}
I'd recommend that you change a few things here. Are you familiar with object-oriented design? If not, it's highly recommended that you read about that if you're looking to write code in C++ (Or just writing code in general, as it's a pretty major aspect of many programming languages)
Consider treating each of your menus and submenus as individual objects. Each time you enter the loop, use an object pointer to call a method that prints the current menu text.
Then, take the input from the user as normal, and change the menu object you're using now.
This is perhaps not the most ideal way to do a console menu, but it will give you a very strong grounding in how objected-oriented programming works.
I've attached an example :
#include <iostream>
#include <string>
class BaseMenu
{
public:
BaseMenu() { m_MenuText = "This shouldn't ever be shown!"; } // This is the constructor - we use it to set class-specific information. Here, each menu object has its own menu text.
virtual ~BaseMenu() { } // This is the virtual destructor. It must be made virtual, else you get memory leaks - it's not a quick explaination, I recommend you read up on it
virtual BaseMenu *getNextMenu(int iChoice, bool& iIsQuitOptionSelected) = 0; // This is a 'pure virtual method', as shown by the "= 0". It means it doesn't do anything. It's used to set up the framework
virtual void printText() // This is made virtual, but doesn't *have* to be redefined. In the current code I have written, it is not redefined as we store the menu text as a string in the object
{
std::cout << m_MenuText << std::endl;
}
protected:
std::string m_MenuText; // This string will be shared by all children (i.e. derived) classes
};
class FirstMenu : public BaseMenu // We're saying that this FirstMenu class is a type of BaseMenu
{
FirstMenu()
{
m_MenuText = "Main Menu\n" // What we are doing here is setting up the string to be displayed later
+ "Please make your selection\n" // What we are doing here is setting up the string to be displayed later
+ "1 - Start game\n" // What we are doing here is setting up the string to be displayed later
+ "2 - Options\n" // What we are doing here is setting up the string to be displayed later
+ "3 - Quit\n" // What we are doing here is setting up the string to be displayed later
+ "Selection: "; // What we are doing here is setting up the string to be displayed later
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done "options". You would obviously need to do this for all of your menus
{
case 2:
{
aNewMenu = new SecondMenu; // We're creating our new menu object here, and will send it back to the main function below
}
case 3:
{
// Ah, they selected quit! Update the bool we got as input
iIsQuitOptionSelected = true;
}
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
class SecondMenu : public BaseMenu
{
SecondMenu()
{
m_MenuText = "OptionsMenu\n"
+ "Please make your selection\n"
+ "1 - ????"
+ "2 - dafuq?";
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done options. You would obviously need to do this for all of your menus
{
case 1:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
case 2:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
int main (int argc, char **argv)
{
BaseMenu* aCurrentMenu = new FirstMenu; // We have a pointer to our menu. We're using a pointer so we can change the menu seamlessly.
bool isQuitOptionSelected = false;
while (!isQuitOptionSelected) // We're saying that, as long as the quit option wasn't selected, we keep running
{
aCurrentMenu.printText(); // This will call the method of whichever MenuObject we're using, and print the text we want to display
int choice = 0; // Always initialise variables, unless you're 100% sure you don't want to.
cin >> choice;
BaseMenu* aNewMenuPointer = aBaseMenu.getNextMenu(choice, isQuitOptionSelected); // This will return a new object, of the type of the new menu we want. Also checks if quit was selected
if (aNewMenuPointer) // This is why we set the pointer to 0 when we were creating the new menu - if it's 0, we didn't create a new menu, so we will stick with the old one
{
delete aCurrentMenu; // We're doing this to clean up the old menu, and not leak memory.
aCurrentMenu = aNewMenuPointer; // We're updating the 'current menu' with the new menu we just created
}
}
return true;
}
Note that this might be a bit complex for starting out. I strongly recommend you read the other answers people have posted. It should give you a few approaches on how to do it, and you can progress from the basic up to the more complex, examining each change.
Looking at what you are trying to do, I would change how you are ensuring the user still want's to play the game first. Look at using a while loop to check if a variable is true or false (people tend to use boolean variables(bool's) for this, an int set to 1 or 0 will do the same). That removes the need for the do-while. Reading up on control logic (if/else, while, for loops) and logical operators (&& - and, || - or, != - not equal to) is recommended. Control logic makes your code do different things, booleans are quick for checking yes/no scenarios and logical operators allow you to check multiple items in one if statement.
Some reading: Loops
Edit: Have more links for reading material, don't have the rep to post them.
Secondly, use another variable (int or whatever suits you) to track what screen you are on.
Based on this selection, display different options but still take input 1,2,3 to decide upon the next action.
In some terrible pseudo-code here is what I would lean towards:
main()
{
int choice
int screen = 1
bool running = true
while(running) {
//Screen 1, Main menu
if(screen == 1) {
cout << stuff
cout << stuff
cout << option 1
cout << option 2
cout << option 3
cout << selection:
cin >> choice
}
else if(screen == 2){
//options screen here
}
else {
//default/error message
}
//add some choice logic here
if(screen == 1 && choice == 3){
//being on screen one AND choice three is quit
running = false;
}
else if(screen == 1 && choice == 2){
//etc..
}
}
}
This is my first proper answer, all terrible criticism is well recieved.

create menus in command line

How can one create menus in the command line program? I've tried stuff like:
cin >> input;
switch (input) {
case (1):
// do stuff
case (2):
// ...
}
but then I've had the problem of sub-menus, and going back to the same menu, etc. The first program I wrote (apart from exercises) that tried to use the switch idea for the menus had goto statements because the alternative was heaps of (at the time) complicated loops.
If I tried to count the ways in which one might create a 1,2,3 menu, we'd both be dead before I'd iterated 1/2 of them. But here's one method you could try to get you started (untested, you may need to clean up a couple things):
struct menu_item
{
virtual ~menu_item() {}
virtual std::string item_text() const = 0;
virtual void go() = 0;
};
struct print_hello_item
{
std::string item_text() const { return "display greeting"; }
void go() { std::cout << "Hello there, Mr. User."; }
};
struct kill_everyone_item
{
std::string item_text() const { return "Go on murderous rampage"; }
void go() { for(;;) kill_the_world(); }
};
struct menu_menu_item
{
menu_menu_item(std::string const& text) : text_(text), items() {}
void add_item(std::unique_ptr<menu_item> item) { items.push_back(std::move(item)); }
void go()
{
std::cout << "Choose: \n";
std::for_each(items.begin(), items.end(), [](std::unique_ptr<menu_item> const& item)
{
std::cout << "\t" << item->item_text() << "\n";
});
std::cout << "\n\n\tYour choice: ";
int choice = get_number_from_console();
if (items.size() > choice) items[choice]->go();
}
std::string item_text() const { return text_; }
private:
std::string text_;
std::vector<std::unique_ptr<menu_item> > items;
};
int main()
{
menu_menu_item top_item;
top_item.add(std::unique_ptr<menu_item>(new print_hello_item));
top_item.add(std::unique_ptr<menu_item>(new kill_everyone_item));
top_item.go();
}
As an exercize, how might I define menu items like so:
top_level.add()
( "Drive off a cliff", &die_function )
( "Destroy the world", &global_thermal_nuclear_war )
( "Deeper", submenu()
( "Hey, check this shit out!", &gawk ))
;
It can be done with the above framework as a starting point.
This is the difference between OO design and what might be called "procedural". I created an abstraction behind what it means to be a menu choice (which can be another menu) that can be extended in various directions. I create the extensions I need, put them together, and tell the thing to go. Good OO design is just like that...the main part of your program is comprised of putting stuff together and telling it to go.
The key thing to take from this is not necessarily to do it the way I just did, but to think about it in a different way. If you can get the gist of the above code then you'll see that you can add new items, with new menus, to arbitrary depths, without having to deal with the kind of overly complicated code that the switch style causes.
You can integrate submenus in your menu with your method:
cin >> input;
switch (input) {
case (1):
cin >> input;
switch (input) {
case (1): //do stuff
case (2): //do stuff
}
break;
case (2):
break;
}
Is this what you're looking for? Otherwise: What do you want to solve exactly?
Edit:
So what you need is an additional loop in your sub-menus with an break condition?
do{
cin >> input;
switch (input) {
case (1):
do{
cin >> input;
switch (input) {
case (1): //do stuff
case (2): //do stuff
}
}while(input != 3);
break;
case (2):
break;
}
}while(true);
I just asked a similar question at Libraries for displaying a text-mode menu? -- it looks like ncurses will dramatically simplify the menu-displaying parts.

Advanced switch statement within while loop?

I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But..
Lets say I have the following scenario (theorietical code):
while(1) {
//Loop can be conditional or 1, I use it alot, for example in my game
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
break;
case 'b':
cout << "...";
break;
}
}
And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements?
This obviously looks wrong:
case 'a':
cout << "You entered A, which is correct";
break;
break;
So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple?
This would solve a lot of my problems that I have right now.
I would refactor the check into another function.
bool is_correct_answer(char input)
{
switch(input)
{
case 'a':
cout << "You entered A, which is correct";
return true;
case 'b':
cout << "...";
return false;
}
return false;
}
int main()
{
char input;
do
{
std::cout << "Enter something\n -->";
std::cin >> input;
} while (!is_correct_answer(input));
}
You could simply have the while loop check for a bool value that is set within one of your case statements.
bool done = false;
while(!done)
{
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
done = true; // exit condition here
break;
case 'b':
cout << "...";
break;
}
}
Yes, C and C++ have no way to say "exit multiple breakable blocks" (where a "breakable block" is any loop or switch). Workarounds include gotos and use of boolean variables to record whether an outer "breakable block" should also break (neither is elegant, but, that's life).
Two break statements will not get you out of the while loop. The first break only gets you out of the switch statement and the second one is never reached.
What you need is to make the condition of the while loop false, assuming that there is nothing in the loop after the switch statement. If there is other code after the switch, you should check the condition after the switch, and break there.
bool done = false;
while(! done)
{
// do stuff
switch(something)
{
case 'a':
done = true; // exit the loop
break;
}
// do this if you have other code besides the switch
if(done)
break; // gets you out of the while loop
// do whatever needs to be done after the switch
}
You could try:
Using Flags
Using Goto
Having the Inner Breakable block into a function
Using Exceptions
Using longjump and setjmp
A topic very similar to this question
http://www.gamedev.net/community/forums/topic.asp?topic_id=385116
You might be interested in the named loop idiom in C++.
#define named(blockname) goto blockname; \
blockname##_skip: if (0) \
blockname:
#define break(blockname) goto blockname##_skip;
named(outer)
while(1) {
//Loop can be conditional or 1, I use it alot, for example in my game
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
break(outer);
case 'b':
cout << "...";
break(outer);
}
}
You can also encapsulate the loop into a function and call return inside the case, for the case that the flag breaking the while is not enough.
It is not a good programming practice for some people but if you keep the function simple I don't see why not.
You could replace the switch with a slightly over-engineered OO solution...
#include <iostream>
#include <map>
#include <set>
class input_responder
{
std::set<char> correct_inputs;
std::map<char, const char*> wrong_inputs;
public:
input_responder()
{
correct_inputs.insert('a');
wrong_inputs['b'] = "...";
}
bool respond(char input) const
{
if (correct_inputs.find(input) != correct_inputs.end())
{
std::cout << "You entered " << input << ", which is correct\n";
return true;
}
else
{
std::map<char, const char*>::const_iterator it = wrong_inputs.find(input);
if (it != wrong_inputs.end())
{
std::cout << it->second << '\n';
}
else
{
std::cout << "You entered " << input << ", which is wrong\n";
}
return false;
}
}
};
int main()
{
const input_responder responder;
char input;
do
{
std::cout << "Enter something\n -->";
std::cin >> input;
} while (responder.respond(input) == false);
}
You could change your switch to an ifsystem. It will be compiled to the same thing anyway.