Password control, exiting Do Loop, Returning to main

Hi

I am testing to see if a correct password is entered in 3 attempts, if it is not, the program exits, if its correct, it return back to the main. I made a try but not sure how to finish it off. Cant get it to display the "test" message.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
using namespace std;

void Login()
{
     int j=1;
     string password;
     string pass;
          
     ifstream infile("Pass.txt");
     if (infile.fail())
     {
         cout<<"Error! Cannot read the file ";
         exit(1);
     }
     getline(infile,password);
   
do
{
     cout<<"------------------------------------\n";
     cout<<"Please enter the password; Attempt "<<j<<": \n";
     cin>>pass;
     j++;
}while(pass!=password&&j<4);
  
cout<<"You have entered the incorrect password too many times.\n";
exit(1);
}

int main()
{
    int resp;
    
    cout<<"Welcome\n";
    cout<<"1.LOGIN\n";
    cout<<"2.ABOUT\n";
    cout<<"3.EXIT\n";
    cin>>resp;
    
    if(resp==3)
    {
         exit(1);
    }
    else if(resp==2)
    {
         cout<<"about";         
    }
    else if(resp==1)
    {
         Login();
         cout<<"Test";           
    }     
system("Pause");
}      
exit(1); get rid of it.
Yeah but if I remove exit(1); , no matter the inputs, it always goes straight back to the main function instead of exiting there if 3 incorrect passwords are entered.
exit() terminates the whole program. There is also return. See
http://www.cplusplus.com/doc/tutorial/functions/

One can use return in function that returns no value:
1
2
3
4
5
6
7
8
void foo( int a ) {
  // code
  if ( .... )
  {
    return;
  }
  // code
}

There is an implicit return; at the end of such function.

From that follows that the exit(1) at line 28 is the problem. However, I would change the void Login() into bool Login() and return false; on line 15 and line 28.

However, you do have a problem in Login(). Your while-loop terminates on two situations:
1. Correct password
2. Too many attempts
But what do you do on lines 27-28? You terminate the program anyway. You should check on line 26 for the true reason and perhaps return true; on "success".


Likewise, return 1; would be fine on line 43, and then return 0; at the end of main().

If you return bool from Login(), then in main() line 51 you can test whether the function was a success:
1
2
3
4
5
6
7
8
if ( Login() )
{
  cout<<"Successful Login";
}
else
{
  return 1;
}
Ahh that made sense. Made the changes and used bool. Worked well thanks
Topic archived. No new replies allowed.