C++ Looping

I asked about repeating a c++ code and i was told recursive functions were the way to go but i just cant figure out how to add it to to my code

lets say:

int main ()
{
cout << "Enter Password" << endl;
cin >> pass;
if(pass == "test"){
cout << "Accepted" << endl;
}
}else{
cout << "WRONG" << endl;

how can i make it loop back to enter password after wrong?
Just what you said - by using a loop. See http://www.cplusplus.com/doc/tutorial/control/#loops
In this case, recursion really doesn't make sense. You should use a loop instead. I'll show the code for both methods.

This is the recursive solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    cout << "Enter Password" << endl;
    cin >> pass;
    if(pass == "test)
        cout << "Accepted" << endl;
    else
    {
        cout << "WRONG" << endl;
        main(); //call the function again
    }
    return 0;
} 


And the iterative solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
    bool passwordCorrect = false;
    while(!passwordCorrect)
    {
        cout << "Enter Password" << endl;
        cin >> pass;
        if(pass == "test")
        {
            passwordCorrect = true;
            cout << "Accepted" << endl;
        }
        else
            cout << "WRONG" << endl;
    }
    return 0;
}


The loop solution is a bit longer, but is definitely more appropriate for the problem. By using recursion, you use more memory every time main calls itself, and this memory will never be reclaimed unless the correct password is entered. An attacker could theoretically use this to crash your system. The loop, on the other hand, just tells the computer to jump back to the top of the function if the password is wrong, so it doesn't waste memory.
Last edited on
I don't think you are supposed to call main() at all.
@Telion: I know you disapprove of calling it but it's good to notice.

If I were you I would stick for now with loops. Recursion is a bit harsher to learn (and understand) and can wait.
Topic archived. No new replies allowed.