Password Authentication c++

后端 未结 4 1629
野的像风
野的像风 2021-01-25 23:25

Hi this is my first time using classes so apologies for my poor explanation. Basically I am making a password function for an elevator program. LogIn is the name of my class, wh

相关标签:
4条回答
  • 2021-01-25 23:42

    Try this, sweet and simple:

    cout << "nameAttempt: " << endl;
    cin >> nameAttempt; 
    
    LogIn Authenticate(name, nameAttempt);
    attempts = 0;
    while (attempts<2)
    {
        if (Authenticate.getName() == Authenticate.getNameAttempt()) 
        {
          return true;
         }
    
         cout<<"Incorrect name. Try again"<< endl;
         cout<< "" << endl;
    
         cout << "Enter Name:"<< endl;
         cin >>nameAttempt;
         attempts++;
         LogIn Authenticate(name, nameAttempt);
     }
    return false;
    
    0 讨论(0)
  • 2021-01-25 23:49

    You initialize local function variable

    int attempts = 0; 
    

    so exit condition in while loop will be trigerred third times the code

     if (attempts++ ==2)
    

    is run, so you will print two times:

    while (Authenticate.getName() != Authenticate.getNameAttempt())
    {
        if (attempts++ ==2) // increment attempts
    {
        return false;
    }      
    

    It looks as it was done deliberately to exit after second print, so your confusion is hard to understand. Use the debugger, this kind of error is very easy to investigate.

    0 讨论(0)
  • 2021-01-25 23:50

    In the retry loop, you still need to validate the attempted name and break the loop if the name is accepted.

    0 讨论(0)
  • 2021-01-25 23:51

    I think the code should be like this:

    while (1)
        {
            if (Authenticate.getName() == Authenticate.getNameAttempt())
            {
                return true;
            }
            else        
            {
                if (attempts++ == 2)
                {
                    return false;
                }
                cout << "Incorrect name. Try again" << endl;
                cout << "" << endl;
    
                cout << "Enter Name:" << endl;
                cin >> nameAttempt;
    
                Authenticate.setNameAttempt(nameAttempt);
            }
        }
    
    0 讨论(0)
提交回复
热议问题