Controlling number of loops for a 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. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  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;
}
Keep count on how many times you have asked. Use the count to decide.
Can you expand on that a bit? Haven't been using C++ for long so unfortunatley I need things explained in layman's terms
In the code below the integer loop_count is initialised to 0, each time the loop runs it is compared to 3 and then incremented (tip: int++ is use then increment ++int is increment then use). If the count is equal to 3 then the program prints a string and exits with an exits status of 1.

Exit status of 0 implies everything was fine and the program exited normally. Any other number generally means something went wrong, but is program specific. This is why most main functions end with "return 0".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  int A;
  int loop_count = 0;
  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)
        {
        if(loop_count++ == 3) 
        {
             cout << "Exiting after 3 tries" << endl;
             exit(1);
        }
	cout<<"Incorrect password. Try again"<<endl;
	cout << "Please Enter Account Number:" << endl;
	cin >> A;
	cout << "Enter Password Account Password:"<< endl;
	cin >>guess;

}

Last edited on
Topic archived. No new replies allowed.