Reverting to an earlier function

Feb 22, 2012 at 1:32am
I was wondering on how to make a if statement repeat back to itself using a bit of code such as:

1
2
3
4
5
6
7
8
9
10
11
12
int x = 0;
while(x > -5){
    //bit of code I do not know
    cin >> x;
    if (x > 15){
        cout << "Hola" << endl;
    }else if(x > 10){
        cout << "Hello" << endl;
    }else{
        //line of code which reverts to the code I don't know if they enter a invalid piece of code
    }
}

Thanks!
Last edited on Feb 22, 2012 at 1:52am
Feb 22, 2012 at 1:43am
That if statement would repeat itself until x is less than -5. As it stands, it would read in an int, then do something based on the int, either saying Hola or Hello.

I'm not sure what exactly you're looking for, but that loop will keep running unless you escape it.
Feb 22, 2012 at 1:51am
Oh well I used a terrible example, I want something so if they put in a letter or something invalid it will loop back to the input
Feb 22, 2012 at 1:57am
You would have to check for bad input. Something like if (cin.fail()) or if (cin.bad())
Feb 22, 2012 at 2:01am
Thank you
Feb 22, 2012 at 2:10am
But what if I want to loop to a previous place in the function like in this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
        if(chosenAttack == "gust" || chosenAttack == "Gust"){
            PlayerHealth -= 10;
            PlayerStamina -= 1;
        }else if(chosenAttack == "scream" || chosenAttack == "Scream"){
            PlayerHealth -= 10;
            PlayerStamina -= 1;
        }else if(chosenAttack == "veer" || chosenAttack == "Veer"){
            PlayerStamina -= 2;
        }else if(chosenAttack == "heal" || chosenAttack == "Heal"){
            PlayerHealth += 5;
            PlayerStamina -= 1;
        }else{
            //line of code which returns to the top of the if statement
        }
Feb 22, 2012 at 2:19am
Just make the if statement the first part of the loop, and then use recursion.
1
2
3
4
5
6
7
8
do{
    if (stuff)
        // Other stuff
    else if (stuff)
        // Other stuff
    else
        // Don't put anything here
} while (true);


Be careful with while (true), though, because that's an infinite loop. It will never end unless you escape it.
Feb 22, 2012 at 2:20am
Ok thank you
Topic archived. No new replies allowed.