How to break out of switch from a function?

So basically I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// FUNCTION
double function(double input)
if (input < 0)
{
return 0;
}
else {
return input; 
//code
}
// END FUNCTION


//MAIN
int main
{
int menu;
int input;

do {
cout << "Press 1, 2 or 3 (3=quit program).";
cin >> menu;

switch (menu)
{
case 1:
cout << "input 1-5.";
cin >> input;

//CALL FUNCTION (based on "input")

break;

case 2:
//CODE FOR MENU OPTION 2
break;
case 3:
return 0; //QUIT
}
}while(menu != 3)
return 0;


Hope that makes sense. I can post the real code if neeeed be, but I feel like I have a pretty basic question. So when you hit a "break" in one of the switch statements, it goes back to the main menu where you pick option 1, 2, or 3. I want to be able to go to that same menu from within the called function in case the input is less than 0. I tried "return 0;", but it literally just returns the numerical value "0". I tried "break;", but it said I can only use breaks in loops and switch statements. :[

Is there a way to get back to that menu in "main" from a function without putting code in main itself? Thanks!
Last edited on
Well, the way to do it would be to make it so that case 3 just breaks out of the switch. Make the do-while loop only repeat when the choice was 3. If they input, say, 4, make a default case to take care of that.
closed account (1CfG1hU5)
...........
Last edited on
@Ispil

Alright...I'm about to be retarded, so yay for you.

Perhaps I don't know how switches work fully. Does "case 3" mean when the input is "3", that's the case it goes to? So if it was "case duck" then if the input was "duck" it would go to that case?

...

When they input "3" I want the console to close (as I'm sure you know). but you reccommend I do:
1
2
3
4
5
6
7
8
//...
case 3:
break;

case 4:
return 0;
}while(menu != 4)
//... 


something like that? (probably not)
Well, what I recommend is that you do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
do
{
    std:: cout << "Please enter a choice." << endl;
    std::cin >> menu;
    switch(menu)
    {
        //...
        case 3:
            break;
        default:
            std::cout << "Error! Bad input! Please try again." << endl;
            break;
    }
}while(menu != 1 && menu != 2);


That way, when the user types in a 1 or a two, the loop ends. Anything else, and they're going back again.
Topic archived. No new replies allowed.