Originally Posted by
Shedrack Ayaro
What if I want to let the user know the number of trials left...? Like "2 attempts left", "1 attempt left"?...
This is a very old thread! I haven't played with C++ for quite awhile but I imagine instead of going from 1 attempts to 3, maybe reverse that and start at 3 and use that counter as a text prompt. Something like this, from the top of my head:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password = "123";
string passwordEntry;
int attempts = 2;
cout << "Please enter your password (you have 3 attempts): ";
getline(cin, passwordEntry, '\n');
while (passwordEntry != password && attempts > 0)
{
cout << "Please try again: ";
getline(cin, passwordEntry, '\n');
attempts--;
cout << "You have " << attempts << " attempts left."
}
if (passwordEntry == password && attempts > 0)
{
cout << "Access granted";
}
else
{
cout << "Sorry, only allowed 3 attempts";
}
}
As I said, it's been awhile, not sure if this is the correct way to concatenate a string in C++ (line 23, maybe it should be a '+'), or whether this actually works. I'm sure this will give you an idea though to complete it yourself.
Good luck.
Sam.