Password Authentication c++ - 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;

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

Checking for Char/Int

Alright so I am doing an assignment and am getting frustrated. The assignment wants me to ask the user for a number then say if the number is even or odd, but if the user types "done" the program will exit.
So my question is how do you check the input for character/int at the same time, then decide which it is.
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
bool isEven(int userAnswer);
using namespace std;
int userAnswer;
int main()
{
cout << "Which number would you like to check?" << endl;
cin >> userAnswer;
if (isEven(userAnswer) == false)
{
cout << userAnswer << " is a odd number." << endl;
}
else if (isEven(userAnswer) == true)
{
cout << userAnswer << " is a even number." << endl;
}
cin.get();
cin.get();
return 0;
}
bool isEven(int userAnswer)
{
if (userAnswer % 2 == 0)
{
return true;
}
else
{
return false;
}
}
Read into a string (which works in both cases), then parse the string yourself.
Read into a std::string and exit if done is in the string. Otherwise convert to int and carry on as you are. Hint: see std::stoi

C++, structure database program issues

I apologize if this is in the wrong place. I didn't really see an area where to post specific code problems.
I'm tasked by my professor to create a program that allows a user to insert, edit and print out a database of clients. I'm having a problem with one of my functions, it doesn't seem to be comparing something well. The function is the EditClient function on line 85, the logic problem I'm having is on line 93. I included a few tests in the code that makes me certain it is line 93, for example in the else statement on line 99 I have it printing out the same arguments being used in the comparison. Which works! I'm clueless as to why it's not understanding the comparison.
#include <iostream>
#include <iomanip>
using namespace std;
struct ClientInfo{ // the structure template for the client info
char name[40]; //client name
char state[40]; //client state
char city[40];
int PhoneNumber;
long double AccountBalance; //accounts balance
char PaymentDate; //payment date
};
ClientInfo ClientList[10]; //intializes an array with the data type clientinfo
void MainMenu();
void NewClient(ClientInfo List[]); // prototypes
void ViewClient(ClientInfo List[]);
void EditClient(ClientInfo List[]);
int main(){
MainMenu();
system("pause");
}
void MainMenu(){ //this function is the main menu function
char choice = 4;
bool loop = true;
while (loop){
cout << "Welcome to the client database, enter 1 to view the clients, 2 to edit a client , and 3 to enter an entire new client. 0 to quit" << endl; //main menu prompt
cin >> choice;
if (choice == '1'){
ViewClient(ClientList);
}
else if (choice == '2'){
EditClient(ClientList);
}
else if (choice == '3'){
NewClient(ClientList);
}
else if (choice == '0'){
cout << "thank you for using the client database, closing out now" << endl;
loop = false;
}
else{
cout << "invalid number" << endl;
}
}
}
void NewClient(ClientInfo List[]){//function that goes through cins to insert client data
int desiredTimes = 0; // the number of clients the person wish to enter
cout << "how many clients are you entering ?, your list current has "<<endl;
cin >> desiredTimes;
cout << "entering new client function..." << endl;
for (int cnt = 0; cnt < desiredTimes; cnt++){ // runs the program exactly the amount of times the person wished.
cout << "please enter client name" << endl;
cin.ignore();
cin.getline(List[cnt].name, 40);
cout << "please enter client state" << endl; // the getline is used here because there may be spacings within these first 3 catagories
cin.getline(List[cnt].state, 40);
cout << "please enter client city" << endl;
cin.getline(List[cnt].city, 40);
cout << "please enter client Phone Number" << endl;
cin.ignore(); // this is used to prevent the getline from causing issues with the cin
cin >> List[cnt].PhoneNumber;
cout << "please enter client Account Balance" << endl;
cin >> List[cnt].AccountBalance;
cout << "please enter client Payment Date" << endl;
cin >> List[cnt].PaymentDate;
}
}
void EditClient(ClientInfo List[]){ // function to search for a name requested and display the info
char name[40];
cout << "what is the name of the client you wish to view (be specific)?";
cin >> name;
bool loop = true; // boolean for the loop
int cnt = 0; // position in the array
while (loop){
if (cnt < 11){
if (name == List[cnt].name){ //if true, prints out the client's info
cout << "true";
/*NewClient(List[cnt]);*/
loop = false; // ends the loop
}
else{
cout << name << " " << List[cnt].name << endl;
cnt++;
}
}
else{
cout << "your client isn't in the database M8" << endl;
loop = false;
}
}
}
void ViewClient(ClientInfo List[]){//this function goes through the client list and displays a particular client
cout << "the following is a huge overrun of all the data inside this list, prepare your self." << endl;
for (int cnt = 0; cnt <= 10; cnt++){//goes through until the counter is greater than the size of the list in the parameter
cout << endl;
cout << List[cnt].name;
cout << List[cnt].state;
cout << List[cnt].city;
cout << List[cnt].PhoneNumber;
cout << List[cnt].AccountBalance;
cout << List[cnt].PaymentDate;
}
}
this is the specific line, where i'm having a comparision error.
if (name == List[cnt].name){ //if true, prints out the client's info
if (name == List[cnt].name) is doing a pointer comparison, not a string comparison. This will only be true if name and List[cnt].name point to the same memory location, which they never will. You should probably be using std::string instead of char[], but if you need to use char[] for some reason, you'll need to use the strcmp() function to compare them.
instead of the if statement you are using, trying using this statement,
if (strcmp(name,List[cnt].name)==0){
It should work properly :)

getting a string to work in password function

Hi apologies for my poor explanation I'm very new to this. I am currently working on a password function but I'm having problems. I have set the account name to string "john" and the account password to int 1111. The password works fine but the string is causing the error. When I change "const string name = "john"" into a random integer the code works fine.
I was hoping someone could spot where I'm going wrong?
bool login() {
const int password = 1111;
int passwordAttempt;
const string name = "john";
string nameAttempt;
int attempts = 0;
std::cout << "Please Enter Password:" << std::endl; //first attempt at account number & password
std::cin >> passwordAttempt;
std::cout << "Enter Name:"<< std::endl;
std::cin >> nameAttempt;
if (passwordAttempt == password && nameAttempt == name) {
return true;
}
else
while (passwordAttempt!=password || nameAttempt!=name) {
if(attempts++ ==2)//.. a loop for two more attempts
{
std::cout << "You have entered the wrong details three times. The application will be terminated now" << std::endl;
return false;
break;
}
std::cout<<"Incorrect password. Try again"<<std::endl;
std::cout<< "" <<std::endl;
std::cout << "Please Enter Password:" << std::endl;
std::cin >> passwordAttempt;
std::cout << "Enter Name:"<< std::endl;
std::cin >>nameAttempt;
}
}
using namespace std;
int main() {
bool loggedIn = login();
if (loggedIn){
cout << "Logged In" << endl;
}
else if (!loggedIn){
cout << "Not Logged" << endl;
}
system("pause");
return 0;
}
Add std:: to your string declarations (so you will have std::string).
After while loop there's end of function login without any value return. Add return true there. Also always build with warnings enabled!

Limit Login Attempts in 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;
}
}
}