Limit Login Attempts in C++ - c++

Ok, I've been learning C++ for about 4 days now and it's my first programming language. So what this really means is that I've only got about 8 hours of programming experience and a lot of that was reading the intro to my C++ book and figuring out how to use XCode.
Anyway, my beginner C++ book is asking me to do the following: "Write a password prompt that gives a user only a certain number of password entry attempts so that the user cannot easily write a password cracker."
The only thing is I just now learned loops and I don't think the book has even covered how to limit attempts yet. Can anyone help? I've seen this, but it's too advanced for me and I don't get it. Here's the code: (really basic newb code... sorry if it insults your intelligence)
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
while ( 1 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "billy" && password != "bob" )
{
cout << "Incorrect username/password combination. Please try again." << "\n" <<
endl;
}
else
{
break;
}
}
cout << "Access granted." << endl;
}

The while ( 1 ) { } construct repeats whatever is inside the {} to infinity, unless you explicitly break from the loop. That's a loop, btw.
How could you break from it after a number of attempts? You could have a counter that gets incremented with every attempt and break from the loop at the limit:
if ( ++counter >= limit )
break;
or simply move the condition inside the while
while ( ++counter < limit )
or use a simple for loop or a do {} while().

Take some variable, say attemptCount, which keeps track of number of attempts made. Initialize it to 0 and increment it by 1 with every unsuccessful attempt. Put the condition in while loop checking that the attemptCount is less than the number of allowed attempts (taken 3 in my code below). So, the code will be:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string username;
string password;
int attemptCount = 0;
while ( attemptCount < 3 )
{
cout << "Enter your username: " << endl;
cin >> username;
cout << "Enter your password: " << endl;
cin >> password;
if ( username != "billy" && password != "bob" )
{
cout << "Incorrect username/password combination. Please try again." << "\n" <<
endl;
attemptCount++;
}
else
{
break;
}
}
cout << "Access granted." << endl;
}

Think about how this works:
#include <iostream>
using namespace std;
int main()
{
const int MAXTRYS = 4;
int numTrys = 0;
while(numTrys != MAXTRYS)
{
cout << "Attempting login" << endl;
++numTrys;
}
return 0;
}

Your while(1) loop will go on forever unless you also have some counter that you increment with every failed attempt.
But frankly...why have a while loop and a separate counter? You have a known max number of iterations; that's the kind of case a for loop was made for.
for (int attempts = 1; attempts <= 3; ++attempts) {
... get login info ...
if (...username and password are correct...) {
cout << "Access granted.\n";
return 0;
}
else {
cout << "Invalid login.\n";
}
}
// Note as well, the default case (what happens if they make it through the loop)
// should be no access. Otherwise, someone could just succeed by inputting three
// bad passwords. :P
cout << "Too many invalid login attempts.\nExiting.\n";
return -1;

You should use a for loop, not a while loop then. Something along the lines of:
bool bSuccess = false;
for (int i = 0 ; i < maxAttemps ; ++i)
{
// your stuff
// set bSuccess = true when relevant
}
if (bSuccess)
{
// ok, successfully logged in
}
Infinite loops are often restricted to really infinite loops (waiting for network messages forever until quit, etc.). As a rule of thumb for good practice, try to avoid infinite loops as much as possible, and break constructs too because it's kind of hacky generally. To exercise, you should try to write nice code which translates to an easy dataflow.
I guess you suspect it, but this wouldn't be secure at all (you store username and password in plain text in the code of your executable).

I`m having a hard time re-familiarizing with C++, since highschool ( #8 years ago ) alot has changed, or my informathics teacher was just bad...
I also find the "for" loop better for this kind of exercise but isn't it true that "return 0;" and "break;" do the same thing?
This is what I worked out with what I saw here and what I already "knew" :). Works like a charm.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int attempts = 0;
string password;
for (int attempts = 0; attempts < 5; ++attempts )
{
cout << "enter your password! \n";
cin >> password;
++attempts;
if ( password == "boo123" )
{
cout << "granted!";
return 0;
}
else
{
cout << "denied! \n";
}
}
}
and 1 more thing: all loops are infinite 'till you "break;" it or "return 0;" it...

/*Write a password prompt that gives a user only a certain number of password entry attempts—
so that the user cannot easily write a password cracker*/
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string password;
int x = 1;
while (1) //This creates an overall top level infinite loop
{
cout << "Input password here: ";
cin >> password;
if ( password == "teddy") //This sets the condition for success
{
cout << "Access Granted!!!!";
break; //The break is applied here to stop the cycle after success is made
}
else if ( password != "teddy") //This sets the condition for failure
{
cout << "Wrong username/password" << "\n" << x << " " << "wrong attempts" << "\n";
++x;
if ( x > 5 ) // This is the counter limit portion. Limit set to 5 attempts
{
break;
}
}
}
}

#include <iostream>
using namespace std;
int main()
{
string password;
int pCounter = 0;
cout << "Enter Password here: ";
getline(cin, password);
while(pCounter <= 4){
if(password != "winner"){
cout << "Count: " << pCounter << endl;
cout << "Try again..wrong entry.." << endl;
cout << "Enter Password here: ";
getline(cin, password);
++pCounter;
if((password != "winner") && (pCounter == 4)){
cout << "The End..No more tries!!" << endl;
break;
}
}
else{
cout << "Welcome In Bro" << endl;
break;
}
}
return 0;
}

include
using namespace std;
int main() {
string password = "set"; //declaring the password
string input; //declaring a string for input later
for (int attempt = 1; attempt <= 3; attempt++) { //if you fail the password 3 times you get kicked out
cout << "enter password " << flush;
cin >> input;
if (input == password) { //checks to make sure the user input matches set password
cout << "granted";
return 0; //once correct password is put in the program ends
}
else { //if password is wrong repeat till right or 3 trys
cout << "you fail" << endl;
}
}
}

Related

How to make program shut itself after 3 wrong passwords in C++?

I need a program that after 1 wrong password it shows certain messege, after 2 wrong tries shows diffrent messege and after 3rd one it shut itself off. Of course after correct password it should turn the program on.
It has to contain do...while.
Here's the part of the code that should operate passwords (if there are any difficulties with language I can translate but it's just passwords and messeges to show):
int licznik = 0; // licznik => counter
string ha; // ha short hand for haslo => passowrd
cout << "Podaj haslo:" << endl; // Prodaj => to try, to pass
cin >> ha;
if (ha != "haslo" && licznik < 3)
cout << "Haslo bledne, sprobuj jeszcze raz!" << endl;
// blende => wrong
// jeszcze => once
// raz => again
else
cout << "Haslo prawidlowe!";
// prawidlowe => correct
do {
licznik++;
if (licznik <= 2)
cout << "Ostatnia szansa!!!!!" << endl;
// Ostatnia => final
// szansa => chance
else {
exit(0);
}
} while (ha == "haslo");
The solution is quite easy to achieve even without using statements like goto or nested conditions in a very simplified manner (read the comments for explanation):
#include <iostream>
int main(void) {
std::string password;
int chances = 3;
do {
// Get the user input (could be multispaced)
std::getline(std::cin, password);
if (password == "haslo")
break;
// Conditioning the attempts
if (chances != 0) {
std::cout << "You have " << chances-- << " left\n";
continue;
} else {
std::cerr << "Password invalid.\n";
return -1;
}
} while (true);
std::cout << "Access granted.\n";
return 0;
}
Here's a sample test case:
rohanbari#genesis:~/stack$ ./a.out
hello
You have 3 left
there
You have 2 left
haslo
Access granted.
I am Slavic descent, but I cannot read polish thus it is hard for me to understand exactly what you mean, and what you want, but my best guess is that you wanted something like this:
#include <iostream>
using namespace std;
int main (void) {
int licznik = 0;
string ha;
cout << "Enter password:" << endl;
do {
if (licznik > 2) {
std::cout << "You entered password too many times";
exit (0);
} else if (licznik > 0)
cout << "You entered wrong password "
<< licznik << " times. Try again: "
<< endl;
cin >> ha;
licznik++;
} while (ha != "haslo");
std::cout << "Success you are logged in" << endl;
return 0;
}
Try this, It might be helpful for you to learn
Here I have use multiple goto statement within if conditions in do-while loop. Basically goto statement is an unconditional jump statement used for transferring the control of a program. you can also learn goto statement here.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string pass;
int x = 0;
a: // when two tries are left
b: // when 1 try is left
cout << "Enter password : " << ' ';
cin >> pass;
if (pass != "password" && x < 3)
{
cout << "Password incorrect\n";
do
{
x++;
if (x == 1)
{
cout << "please try again (2 try left)\n\n";
goto a;
}
else
if (x == 2)
{
cout << "please try again (1 try left)\n\n";
goto b;
}
else
if (x == 3)
{
cout << "terminating\n\n";
exit(1);
}
} while (x <= 3);
}
else
{
cout << "Password is correct\n\n\n";
}
return 0;
}
Sample Output:
Enter password : World
Password incorrect
please try again (2 try left)
Enter password : prom
Password incorrect
please try again (1 try left)
Enter password : password
Password is correct

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}

Password Authentication c++

Hi this is my first time using classes so apologies for my poor explanation. Basically I am making a password function for an elevator program. LogIn is the name of my class, which contains the string "john" which is the password. Everything seems to be working fine except the loop for incorrect password attempts.
If the password attempt is correct the first time then the code workds fine, however if a password is entered incorrectly then the line "Incorrect name. Try again" appears for the next two attempts, regardless of whether or not the password has been entered correctly. I was hoping someone could see where I'm going wrong. name is the stored password and nameAttempt is the attempted password inputted bu the user.
#include "stdafx.h"
#include "LogIn.h"
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
bool password() {
string name;
string nameAttempt;
int attempts = 0;
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2)
{
return false;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
}
}
int main()
{
bool password();
bool loggedin = password();
if(loggedin) {
cout << "Password Correct" << endl;
}
if(!loggedin) {
cout << "Incorrect Password" << endl;
cout << "Program will now terminate" << endl;
system("pause");
return 0;
}
cout << "you are now free to enter lift" << endl;
system("pause");
return 0;
}
In the retry loop, you still need to validate the attempted name and break the loop if the name is accepted.
You initialize local function variable
int attempts = 0;
so exit condition in while loop will be trigerred third times the code
if (attempts++ ==2)
is run, so you will print two times:
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2) // increment attempts
{
return false;
}
It looks as it was done deliberately to exit after second print, so your confusion is hard to understand. Use the debugger, this kind of error is very easy to investigate.
I think the code should be like this:
while (1)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
{
if (attempts++ == 2)
{
return false;
}
cout << "Incorrect name. Try again" << endl;
cout << "" << endl;
cout << "Enter Name:" << endl;
cin >> nameAttempt;
Authenticate.setNameAttempt(nameAttempt);
}
}
Try this, sweet and simple:
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
attempts = 0;
while (attempts<2)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
attempts++;
LogIn Authenticate(name, nameAttempt);
}
return false;

How do I use cin in a while loop?

I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}
You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}
Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?

Do/While loop not looping

I am a beginner in C++ and I was doing a do/while loop exercise and I am having trouble with it recognising the condition let alone it not looping properly. Can you guys give me a good foundation on how a simple problem like this is solved? I want to try and use a string to fulfill the condition of the do/while loop.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double mean = 0;
string continuer;
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, continuer);
cout << "something" << endl;
cin >> mean;
}
while (continuer == "Y" || continuer == "y");
return 0;
}
What I gather from your question and comment, you want to iterate through the loop at user's will.
You just want a char variable for that, like this.
string input ;
int number = 0 ;
do
{
cout << "Please enter a number" << endl ;
cin >> number ;
cout << "If you want to continue, Press Y" << endl ;
cin >> input ;
} while (input == "Y" || input == "y") ;
This do-while loop will execute at least one time, because the condition gets checked at the end of the loop execution. So even if the user does not press Y when asked the first time, this loop would have been executed once. After that, it will go on as long as the condition is fulfilled.
Learn more about the do-while loop here.
http://www.cplusplus.com/doc/tutorial/control/
What do you see? The body of the loop should be executed at least once. Does that happen?
Also, Continuer can be longer than one character, for instance "Y\n". Do test for that.
Here is what I would do:
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double number = 0;
string continuer;
int loop = 0
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, number);
cout << "something" << endl;
cin>> mean;
getline (cin, continuer);
cout << "Your answer was '" << continuer << "'." << endl;
loop = strcmp("Y", continuer);
if (loop != 0) strcmp("y", continuer);
if (loop == 0) cout << "Your choice is to stop." << endl;
else cout << "Your choice is to continue." << endl;
} while (loop == 0);
cout << "Bye" << endl;
return 0;
}
Be as explicit as you can untill you are confident enough in the language and the algorithm you are working with. It is easier to see what is happening and when it works it is easy to remove the 'cout' lines.