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";
}
Related
This code is supposed to be a login and registration system but it actually works I just want to know if there are places I can improve upon on
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <conio.h>
using namespace std;
void RegUser (){
string username, password, un, pw;
ofstream users ("users.txt", ios::app);
cout << "REGISTER USERNAME: " ; cin >> username;
cout << "REGISTER PASSWORD: "; cin >> password;
ifstream users_c ("users.txt");
while (users_c >> un >> pw){
if (username.compare(un) == 0 || password.compare(pw) == 0)
{
cout << "USERNAME OR PASSWORD ALREADY IN USE\n";
}
}
users_c.close();
users << username << endl << password << endl;
users.close();
}
int Login(string username, string password){
string un, pw; int access = 0;
ifstream users ("users.txt");
while (users >> un >> pw){
if (username.compare(un) == 0 && password.compare(pw) == 0)
{
access++;
break;
}
}
users.close();
return access;
}
void menu () {
cout << "[1] TO LOGIN\n";
cout << "[2] TO REGISTER\n";
cout << "ENTER COMMAND: ";
}
main () {
int cho, stop = 0, access;
string username, password;
do {
menu(); cin >> cho;
switch (cho)
{
case 1:
cout << "ENTER USERNAME: "; cin >> username;
cout << "ENTER PASSWORD: "; cin >> password;
access = Login(username, password);
if (access == 1){
cout << "ACCESS GRANTED\n"; stop += 1;
}
else {
cout << "LOGIN ERROR\n";
}
break;
case 2:
RegUser();
break;
}
} while (stop != 1);
cout << "MAIN PROGRAM PLACEHOLDER\n";
getch();
}
How it works is the user will choose whether they want to login or register. Once they pick one they will be asked to enter their username or register the username they want.
The RegUser() function first asks for the username and password they want to use and then open the "users.txt" file to check whether the username or password already exists. if it exists it will not register and they will be brought back to the main menu which is the menu() function.
The Login() function has two arguments which are the username and password entered by the user. Once the user had entered their username and password, it will read the file and check if it resembles any of the username and password already registered in the "users.txt" file.
P.S. there are some #include commands that was not even used for the whole login and registration part but please don't mind that I just left it there because I would be using them in the future.
thank you to anyone who will reply! I'm just starting to learn c++ and want to avoid rookie mistakes.
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;
}
Okay so i am working a project where we are storing user input to create a username and password and storing it within a vector. My main issue is that everytime i use the checkLength function it still takes the user's password even though its less than 5 characters for example here's the output i am getting '
Enter your first name.
John
Enter your last name.
Stewart
Enter a password.
abc
Password is not 5 characters. please try again...
/**it displays the message but still
continues instead of making the user input a 5 character password**/
Enter your first name.
Example
Enter your last name.
exmaple
Enter a password.
prob
Password is not 5 characters. please try again...
Enter your first name.
0
Login data entered
JStewa, abc
Eexmap, prob
Press any key to continue . . .
How do I fix this or why is it looping even though the user only entered a three character password!
here is my code
//DISPLAY 8.9 Using a Vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#include "c:\Users\barta\OneDrive\Documents\Visual Studio 2015\Projects\Project 7\Project 7\Validate.h"
int main( )
{
vector<string> data;
string firstName, lastName, login, userName, password;
Validate c;
firstName = "1";
cout << "Enter your first name.\n";
getline(cin, firstName);
while (firstName != "0")
{
cout << "Enter your last name.\n";
getline(cin, lastName);
do
{
cout << "Enter a password.\n";
getline(cin, password);
c.checkLength(password);
lastName = lastName.substr(0, 5);
userName = firstName.at(0) + lastName;
login = userName + ", " + password;
data.push_back(login);
} while (false);
cout << "Enter your first name.\n";
getline(cin, firstName);
}
cout << " Login data entered \n" << endl;
for (unsigned int i = 0; i < data.size(); i++)
{
cout << " " << data.at(i) << endl;
}
system("pause");
return 0;
}
Validate header file:
class Validate
{
public:
Validate(string);
Validate();
bool checkLength(string);
bool checkSpaces();
bool checkUpper();
private:
string password;
static const int LEN = 5;
};
Validate::Validate()
{
}
Validate::Validate(string pass)
{
pass = password;
}
bool Validate:: checkLength(string password)
{
if (password.length() < LEN)
{
cout << "Password is not 5 characters." << " please try again..." << endl;
return true;
}
else
{
return false;
}
}
loop on checking the length and do everything else outside the loop
bool badLength;
do
{
cout << "Enter a password.\n";
getline(cin, password);
badLength = checkLength(password);
} while (badLength);
lastName = lastName.substr(0, 5);
userName = firstName.at(0) + lastName;
login = userName + ", " + password;
data.push_back(login);
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 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!