Loop a set number of times.

I have been trying to make a program that asks for username and password, and if it is wrong it will loop back to the top. But i only want it to loop a set number of times, how can i do this?
this is my code so far

string username;
string password;

cout << "Enter username: ";
getline(cin, username, '\n');

cout << "Enter password: ";
getline(cin, username, '\n');

if (username == "1" && password == "1"){
cout << "Success, you made it!" << endl;
}

else {
cout << "Access denied" << endl;
}
Well this is were boolean variables comes in handy:

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
#include <iostream>
#include <string>

using namespace std;

int main()
{
	bool success;
	string username;
	string password;

do
{
	cout << "Enter username: ";
	cin>>username;

	cout << "Enter password: ";
	cin>>password;

	if (username == "ron" && password == "secret")
	{
	cout << "Welcome Ron!\n";
	success = true;
	}
	else
	{
	cout<<"Login Failed - Please try again.\n";
	success = false;
	}
} while (!success);

return 0;
}
Last edited on
and if you want to loop only a set amount of times, then add a counter.
make a 'tries' variable, increment it everytime the user enters his username or password, if he enters the wrong username or password more that 'certain amount of times' then break out of the loop.

1
2
3
4
5
6
7
8
9
10
11
string username;
cin>>username;
string password;
cin>>password;
++tries;

if ( tries >= 3 )
{
cout<<"Login limit exceeded , please try again in 10 minutes"<<endl;
//blah blah blah
}
Last edited on
Okey, I got it right now. Thank you guys!
Topic archived. No new replies allowed.