Hi everyone,
I was messing around for hours yesterday trying to get a nested for loop working for a password checker when it dawned on me that perhaps I could use a different type of loop instead.
For hours, I made a bunch of loop programs so that I could better visualize what was happening (rather than just repeated numbers), like this one:
Code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int numberOfLoops = 0;
string newLine;
cout << "How many repeats do you want? ";
cin >> numberOfLoops;
cout << "Want the loops separated by a new line? (y/n): ";
cin >> newLine;
for (int i = 0; i < numberOfLoops; i++)
{
cout << "I'm a loop item, let's celebrate!!";
if ( newLine == "y" )
{
cout << '\n';
}
}
cout << "Loop repeated " << numberOfLoops << " times!";
}
I left it yesterday to come back fresh this morning and came up with this:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;
int attempts = 1;
cout << "Please enter your password: ";
getline(cin, password, '\n');
while ( password != "123" && attempts < 3 )
{
cout << "Please try again: ";
getline(cin, password, '\n');
attempts++;
}
if ( attempts < 3 )
{
cout << "Access granted";
}
else
{
cout << "Sorry, only allowed 3 attempts";
}
}
I guess my question this time is that because of my inexperience, I don't know yet which type of loop to choose. I just (maybe naively) presumed that for loops could handle anything and would also cut down on the amout of code.
Is a while loop perfectly suitable for a password check?
I'm sure there's a 'better' way of doing this but a bit stumped for ideas! Any input from you guys/girls is more than appreciated. You've all been a great help so far.
Thanks.
Sam.