Stop Crazy Switch Looping

Hello. I would like to use my switch loop so that when the default is activated, control goes back to the start of that function. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int function1()
{
int a ;
cout << "Input a number to be cool" ;
cin >> a ;
switch(a)
{
case 1:
blah
case 2:
blah
default:
cout << "You're not cool. Try Again" ; /*I don't actually use this. Laugh */

//hear I want the function to restart. I believe it has something to do with clearing 
//the variable a and restarting the function but I'm not exactly sure. I typed function1() ; 
//to restart the function, but it just loops "You're not cool. Try again." I
//think this is because a is still the same every time it loops. 

Any help would be appreciated. Thank you!
Use an actual loop?
E.G. While/For/Do While.

(P.S.: This should go under Beginners section)
No Help at all. Thanks, though. I need the switch to repeat the original question and allow the user to re-enter the variable ( a ) if an incorrect integer or letters are entered.
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
#include <iostream>

int function1()
{
    int a ;
    std::cout << "Input a number to be cool: " ;

    if( std::cin >> a )
    {
        switch(a)
        {
            case 1:
                std::cout << "cool\n" ;
                return a ;
            case 2:
                std::cout << "also cool\n" ;
                return a ;
            default:
                std::cout << "You're not cool. Try Again\n" ;
                return function1() ;
        }
    }
    else
    {
        std::cout << "You did not enter a number. Try Again\n" ;
        std::cin.clear() ; // clear the error
        std::cin.ignore( 1000, '\n' ) ; // throw the junk away
        return function1() ;
    }

}

int main()
{
    std::cout << function1() << '\n' ;
}
1
2
3
4
5
6
int a;
do
{
    a = your_switch_function();
}
while((a > 2) && (a < 0));


easy shmeasy. You can use defines if you expect these max/min values to change and you want to easily modify them later on.

also, I stay away from switches for that reason. I write them correctly (lord knows isalpha() screwes up on windows 8...) but then they just do wacky things like default not being triggered. I typically stick with the good ol' fashion if() statement and specifify exactly what I want. The only trades are efficiency.
Last edited on
Topic archived. No new replies allowed.