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!
Related
I'm creating a program that is password protected. I have a function with a validation loop called getPassword() that allows the user to type in password attempts as many times as they want, but now I want to limit them to only 3 attempts. Would I be able to do this in the getPassword() function or do I have to create another function?
I've tried making the getPassword() into a do while loop and used a for-loop to inside the do while to count how many times the user attempts entering the password and tried to get it to break when the counter reached 3, but that doesn't seem to get me out of the do while loop. Any suggestions?
void getPassword()
{
int i = 0;
string password = "sup";
string userInput;
int wrongPasswords = 0;
for (int i = 0; i < 3; i++)
{
cout << "Please enter your password: " << endl;
cin >> userInput;
cin.ignore(1000, 10);
while (true)
{
if (userInput != password)
{
cout << "Invalid. Please try again. You can only attempt
password 3 times." << endl;
wrongPasswords++;
break;
}//if
if (wrongPasswords == 3)
break;
}//while
}//for
}//getPassword
Edited code:
void getPassword()
{
string password = "sup";
string userInput;
for (int i = 0; i < 3; i++)
{
cout << "Please enter your password: " << endl;
cin >> userInput;
cin.ignore(1000, 10);
if (userInput == password && i < 3)
break;
}
}//getPassword
You can also try with bool instead of void function. Return true if password was correct, exit program after failing three times. For example,
bool getPassword() {
for ( int attempts = 0; attempts < 3; ++attempts ) {
std::string password;
std::cout << "Enter your password: " << password << std::endl;
std::getline(std::cin, password);
if ( password == "1" ) {
std::cout << "Welcome!";
return true;
}
}
return false;
}
In your main function, call getPassword() function,
int main() {
if ( !getPassword() )
return true;
std::cout << std::endl;
}
This seems more elegant and would have used bool instead of void, unless you have reason not to.
Yet another snippet:
bool tryLogin() {
string pwd = "hello";
string inp;
int tries = 1;
while (true) {
cout << "\nEnter password ";
cin >> inp;
if (inp.compare(pwd) == 0) return true;
++tries;
if (tries > 3) {
cout << "\n Max number of trials exceeded\n";
break;
}
}
return false;
}
int main()
{
cout << endl << (tryLogin() ? "Login successful" : "Can't login") << endl;
}
I've made an app that solves some computations with matrices, and I want to authenticate users in order to grant them access when the program starts.
I will show you what I've done already.
int main()
{
const string USERNAME = "claudiu";
const string PASSWORD = "123456";
string usr, pass;
cout << "Enter Username : ";
cin >> usr;
if(usr.length() < 4)
{
cout << "Username length must be atleast 4 characters long.";
}
else
{
cout << "Enter Password : ";
cin >> pass;
if(pass.length() < 6)
{
cout << "Password length must be atleast 6 characters long";
}
else
{
if(usr == USERNAME && pass == PASSWORD)
{
cout << "\n\nSuccessfully granted access" << endl;
}
else
{
cout << "Invalid login details" << endl;
}
}
}
This is how my code looks like. All I want to do is that when I enter a wrong username or a wrong password the program shows the message I wrote and then let me introduce another username and password and when I introduce them correctly, the program starts.
I would make a logged_in variable, then set it to true when the condition is passed and run the whole login process in a while loop:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const string USERNAME = "claudiu";
const string PASSWORD = "123456";
string usr, pass;
bool logged_in = false;
while (!logged_in)
{
cout << "Enter Username : ";
cin >> usr;
if (usr.length() < 4)
{
cout << "Username length must be atleast 4 characters long.";
}
else
{
cout << "Enter Password : ";
cin >> pass;
if (pass.length() < 6)
{
cout << "Password length must be atleast 6 characters long";
}
else
{
if (usr == USERNAME && pass == PASSWORD)
{
cout << "\n\nSuccessfully granted access" << endl;
logged_in = true;
}
else
{
cout << "Invalid login details" << endl;
}
}
}
}
cout << "Passed login!\n";
}
I am currently working on a program, where the user of the program is required to input username and password, and the program will do the search and see if there is such user, if it exists, then proceeding to a screen with further options, or reenter the username.
The username.txt files that stores the username and password includes the following data:(first column is username, and second is password)
john,abc
marry,cde
admin,admin
joseph,1234
My code is as follows, but it doesnt work, after i input username and password, the programs automatically closes. Can you help me with it? Is there something wrong with my parsing the string into 2?
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<math.h>
#include<stdio.h>
using namespace std;
void printoptionsadmin(){
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout\n5.Shutdown" << endl;
}
void printoptions(){
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout" << endl;
}
void main()
{
cout << "Please login." << endl;
stop:
string usertype;//user input
string passtype;//user input
string line;
string manager = "admin";
string managerp = "admin";
string user;//read from file
string pass;//read from file
ifstream openfile("username.txt");
cout << "Enter your username:";
cin >> usertype;
cout << "Enter your password:";
cin >> passtype;
bool found = false;
while (found&&getline(openfile, line))
{
stringstream iss(line);
getline(iss, user, ',');
getline(iss,pass);
if (usertype == manager && passtype == managerp)//admin login
{
void printoptionsadmin();
found = true;
break;
}
else if (usertype== user && passtype== pass)//regular login
void printoptions();
else
{
cout << "Invalid username or password, please start over." << endl;
goto stop;//going back to login screen
}
openfile.close();
}
}
I altered your code a bit, you messed up the found, plus i removed the goto, also you don't have to explicitly close the file, it is closed when the scope is left(RAAI).
I suggest you to add some checks to your code (file ok? read of line ok? ...)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
static const string PASSWORD_FILE("username.txt");
static const string MANAGER_USER = "admin";
static const char DELIM = ',';
void printoptionsadmin() {
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout\n5.Shutdown"
<< endl;
}
void printoptions() {
cout << "Please select an option:" << endl;
cout << "1.Sell Stock\n2.Buy stock\n3.Inquiry\n4.Logout" << endl;
}
string login() {
ifstream passwordFile(PASSWORD_FILE);
string usertype; //user input
string passtype; //user input
cout << "Enter your username:";
cin >> usertype;
cout << "Enter your password:";
cin >> passtype;
for (string userPasswordLine; getline(passwordFile, userPasswordLine);) {
stringstream ss(userPasswordLine);
string user, password;
getline(ss, user, DELIM);
getline(ss, password, DELIM);
if (user == usertype && password == passtype) {
return user;
} // if
} // for
return "";
}
int main() {
cout << "Please login." << endl;
string loggedInUser;
while ((loggedInUser = login()) == "") {
cerr << "Login failed" << endl;
} // while
if (loggedInUser == MANAGER_USER) {
printoptionsadmin();
} else {
printoptions();
} // else
return 0;
}
Each getline() without third parameter will read a new line and it will provide you something that you are not needed here.
So use " " white space as the delimiter in getline() function instead of default "\n".
Also another thing is your while loop condition is always false since found is initialized to false. So it will not go inside while loop
Here is the logic you needed,
bool found = false;
while (found&&getline(openfile, line))
bool found = false;
std::string delimiter = ",";
while (getline(openfile, line, " "))//To read upto each " "(white space instead of next line(\n is default third parameter)
{
/* Splitting the UserName & Password using ','*/
user = line.substr(0, line.find(delimiter));
pass = line.substr(line.find(delimiter)+1, -1);
if (usertype == manager && passtype == managerp)//admin login
{
void printoptionsadmin();
found = true;
break;
}
else if (usertype== user && passtype== pass)//regular login
void printoptions();
else
{
cout << "Invalid username or password, please start over." << endl;
goto stop;//going back to login screen
}
openfile.close();
}
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;
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;
}
}
}