简体   繁体   中英

counting loops on c++ password program

Hi I am creating a simple password program. The program requires the user to enter an account number and password. The following code works fine however the only problem I have is after 3 incorrect attempts I want the program to terminate with an appropriate message. I can't figure out how to get the loop to stop after 3 incorrect attempts and was hoping someone could help me with this. From what I've gathered I think I may have to use a for loop but I just can't seem to get it working properly. Thanks!

    int A;
    string guess;
    const string pass;
    const int number;

cout << "Please Enter Account Number:" << endl;
cin >> A;
cout << "Enter Password Account Password:"<< endl;
cin >>guess;

    while(A!=number || guess!=pass)
    {
cout<<"Incorrect password. Try again"<<endl;
cout << "Please Enter Account Number:" << endl;
cin >> A;
cout << "Enter Password Account Password:"<< endl;
cin >>guess;
    }

How about:

for (int counter = 0; counter < 2 && (A != number || guess != pass); ++counter)
{
    ...
}
int attempts = 0;
while(A!=number || guess!=pass)
{
    if( attempts++ == 3 )
    {
        cout << "Tough luck; exitting ..." << endl;
        break;
    }
    cout<<"Incorrect password. Try again"<<endl;
    cout << "Please Enter Account Number:" << endl;
    cin >> A;
    cout << "Enter Password Account Password:"<< endl;
    cin >>guess;
}
    int A;
    string guess;
    const string pass = /* some value */;
    const int number = /* some value */;

cout << "Please Enter Account Number:" << endl;
cin >> A;
cout << "Enter Password Account Password:"<< endl;
cin >>guess;

int i = 0;
const int MAX_ATTEMPT = 3;
bool success;

    while( ( success = ( A!=number || guess!=pass ) ) && ( ++i < MAX_ATTEMPT ) )
    {
cout<<"Incorrect password. Try again"<<endl;
cout << "Please Enter Account Number:" << endl;
cin >> A;
cout << "Enter Password Account Password:"<< endl;
cin >>guess;
    }

if ( success ) /* other stuff */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM