Dec 22, 2013 at 4:17am UTC
I'm trying to create a password prompt which only allows a user a certain number of entry attempts.
Which loop do I use?
Is the for loop only for numbers? AND do-while loops for passwords?
This is how far i've gotten.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;
}
Last edited on Dec 22, 2013 at 4:31am UTC
Dec 22, 2013 at 5:22am UTC
You need to look at how you are declaring your variables.
Last edited on Dec 22, 2013 at 5:37am UTC
Dec 22, 2013 at 10:32am UTC
The format should be like:
1] Set a constant to the correct password.
2] Set a constant to the max attempts possible.
3] Run a loop till the max attempts have been reached.
4] In the loop ask user for password and check it whether its correct or not.
5] If correct, exit the loop using
break ;
. If wrong continue the loop.
While loops or For loops works best here. For loops are recommended the best.
A sample would be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <string>
int main() {
const std::string PASSWORD = "abc123" ; //This is correct password to check against
const int CHANCES = 3; //This is the max. no. of chances user can get
std::string guess;
for (int i = 1; i<=CHANCES; i++) { //Execute the loop 3 times (until i reaches 4)
std::cout << "Enter password: " ;
std::cin >> guess; //Get the user's password guess
if (guess == PASSWORD) {
std::cout << "Correct password! Access granted!\n" ;
break ; //Exits the loop
}
else {
std::cout << "Incorrect password! " << CHANCES-i << " attempt(s) left\n" ;
}
}
return 0;
}
Last edited on Dec 22, 2013 at 10:32am UTC