Question about looping

Hello. Is there any way to loop a certain code a couple of times then exit while the condition is still true? In this code, I want to give the user 3 chances to input the correct password then give him a text saying "You can't try again". I can do it with 'if' statement but then it would be so long and so tiring. So can anyone tell me what to do?

P.S: I'm still really a beginner so I may not be familiar with some advanced solutions or concepts, so keep it simple please.

1
2
3
4
5
6
7
8
9
10
11
 string password;

cout << "ENTER PASSWORD: ";
cin >> password;

while (password!="burger")
{
    cout << "Wrong password, try again: ";
    cin >> password;
}
cout << "Correct password, welcome";
When you want to prematurely exit a loop, use the break; statement.
You could use a "for" loop:

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

bool PasswordIsGood = false;

string password;

for( int i = 0; i < 3; i++ )
    {
    cout << "ENTER PASSWORD: ";

    cin >> password;

    if( password == "burger" )
        {
        PasswordIsGood = true;

        break;

         }    /*    if( password == ""burger" )    */
    else
        {
        cout << "Wrong password, "try again" << endl;

        }    /*    if( password != ""burger" )    */

    }    /*    for( i < 3 )    */

if( PasswordIsGood )
    {
    ... the rest of your program

    }
else
    {
    cout << "You are not authenticated!" << endl;

    exit( -1 );

    }
try this :
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
#include <iostream>
#include <string>

int main()
{
	std::string password;
	int nChances = 3;
	bool successful = false;
	do
	{
		std::cout << "Enter password" << std::endl;
		std::cin >> password;
		if(std::strcmp(password.c_str(),"burger") == 0)
		{
			successful = true;
			break;
		}
		--nChances;
	} while( nChances > 0);

	std::cout << ( successful ? "Correct password, welcome" : "could not logged " ) << std::endl;
	
	system("pause");
	return 0;
}
Topic archived. No new replies allowed.