Using Loops

I'm trying to create a password prompt which only allows a user a certain number of entry attempts.

Which loop do I use?

Is the for loop only for numbers? AND do-while loops for passwords?

This is how far i've gotten.

1
2
3
4
5
6
7
8
9
10
11
  #include <iostream>
#include <string>

using namespace std;

int main()
{
    string password;
    
   
}
Last edited on
For loops are generally for a set number of attempts. Though you can modify any loop into another loop type.

Basically it would be like this..


loop starts at a value of 0 attemps..after they guess increment the amount of attempts by one...if it is right then exit the loop

So something like this:

 
for( int attempts = 0; attempts < max_attempts && guess != password; ++attempts )
God.. this is frustrating. Probably not on the right track.

Do you know any resources that go into Loops in depth?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string attempts;
    string password;
    string guess;
    string max_attempts;

    for ( int attempts = 0; attempts < max_attempts && guess != password; ++attempts)
        
       {cout << "Please enter password";
        cin >> password;
        
        if ( password == guess)
        {
            cout << "You have successfully logged in";
        }
else 
    {
        cout << "Wrong password. Try again."
    }
}
    
You need to look at how you are declaring your variables.
Last edited on
Yeah like cody mentioned I would suggest you look at data types there are more than just std::strings.

http://www.cplusplus.com/doc/tutorial/variables/
The format should be like:
1] Set a constant to the correct password.
2] Set a constant to the max attempts possible.
3] Run a loop till the max attempts have been reached.
4] In the loop ask user for password and check it whether its correct or not.
5] If correct, exit the loop using break;. If wrong continue the loop.

While loops or For loops works best here. For loops are recommended the best.

A sample would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

int main() {
    const std::string PASSWORD = "abc123"; //This is correct password to check against
    const int CHANCES = 3; //This is the max. no. of chances user can get
    std::string guess;
    
    for(int i = 1; i<=CHANCES; i++) { //Execute the loop 3 times (until i reaches 4)
        std::cout << "Enter password: ";
        std::cin >> guess; //Get the user's password guess
        if(guess == PASSWORD) {
            std::cout << "Correct password! Access granted!\n";
            break; //Exits the loop
        }
        else {
            std::cout << "Incorrect password! " << CHANCES-i << " attempt(s) left\n";
        }
    }
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.