Reverting to an earlier function

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
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.
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
You would have to check for bad input. Something like if (cin.fail()) or if (cin.bad())
Thank you
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
        }
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.
Ok thank you
Topic archived. No new replies allowed.