I'm trying to create a system in c++ to allow users to log into an account for a personal project and I want to encrypt and store usernames and passwords, but can't figure out how to do so. I have spent a lot of time trying to figure out how encryption algorithms work, but to no avail. I also need it to be able to ensure there are no username clashes. This means being able to read usernames from a document and compare them. I am fairly new to code so if you could dumb it down for me that would be appreciated. I would be grateful for any and all help. Thanks.
This is what I have so far, it's not much but I'm trying not to make it too convoluted until I can figure out how to make it work properly.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
class newUser {
public:
void signUpAttempt() {
cout << "Pick a Username\nUsername: ";
cin >> newUserAttempt;
if (newUserAttempt == "existing username") {
}
}
private:
string newUserAttempt;
};
bool login() {
string isNew;
string userNameGuess;
//checks if the user already has an account
cout << "Have you played before? (y/n)\n";
getline(cin >> ws, isNew);
transform(isNew.begin(), isNew.end(), isNew.begin(), ::tolower); // transforms to lower case
if (isNew == "y" || isNew == "yes") {
newUser Obj1; // creates object
Obj1.signUpAttempt();
}
//ask for username and password
cout << "Enter Username and Password.\n Username: ";
cin >> userNameGuess;
return true; // tells main that user is logged in.
}
int main() {
while (login() != true) {
login();
}
}
Related
Good day everyone! First off all I want to let you all know that I am a beginner at C++, so my code will have a lot of errors.
I was trying to make a program to refresh my concepts of C++. The problem I am facing is the program is asking me the email ID, but as soon as I input it, the program ends. Please let me know everything I am doing wrong and how to correct it. Thank you so much!
I decided to create a simple login program with the following algorithm:
It asks the user for their email ID.
Checks if the email is registered (in a text file)
If the email is registered, the user is prompted for the password.
If the password is correct, a success message is printed; if not, the user s given 2 more attempts.
If the email is not registered, the program prompts the user to enter a new password and tells them the password strength. An ideal password should have an uppercase letter, a lowercase letter and a digit, with the password length more than 6 characters.
data.h:
#include <iostream>
#include <string>
using namespace std;
#ifndef DATA_H
#define DATA_H
struct newAccount{
string email, password; //declaring email and password of the user
};
string readEmail(string email); //reads in the email id provided
void checkEmail(); //checks if the entered email address exists in the system
int addEmail(); //checks if the entered email address exists in the system
void checkPassword(); //checks if the password matches an already registered email id
void makeNewPassword(string& password); //this function helps the user create a secure password
#endif
data.cpp:
#include <iostream>
#include <string>
#include <fstream>
#include "data.h"
using namespace std;
newAccount tempAccount;
string readEmail(string email) //reads in the email id provided
{
cout << "Enter an email address: ";
getline(cin, tempAccount.email);
email = tempAccount.email;
return tempAccount.email;
}
void checkEmail()
{
ifstream file("database.txt");
string str;
while (getline(file, str))
{
if (str == tempAccount.email)
{
cout << "This email is already registered. Please enter your password: ";
getline(cin, tempAccount.password);
checkPassword();
}
else
{
cout << "This email is not registered. Please create a new password: ";
makeNewPassword(tempAccount.password);
}
}
}
int addEmail() //checks if the entered email address exists in the system
{
ofstream myFile("database.txt");
if (myFile.is_open())
{
myFile << tempAccount.email << endl;
myFile.close();
}
else
cout << "Unable to open file";
return 0;
}
void checkPassword() //checks if the password matches an already registered email id
{
ifstream file("database.txt");
string str;
while (getline(file, str))
{
if (checkEmail)
{
if (str == tempAccount.password)
{
cout << "Login successful! ";
getline(cin, tempAccount.password);
}
else
for (int i = 4; i > 1; i--)
{
cout << "Incorrect password! You have " << i - 1 << " tries remaining.\n";
if (str == tempAccount.password)
break;
}
}
}
}
void makeNewPassword(string &password) //this function helps the user create a secure password
{
int n = password.length();
bool hasLower = false, hasUpper = false, hasDigit = false;
for (int i = 0; i < n; i++)
{
if (islower(password[i]))
hasLower = true;
if (isupper(password[i]))
hasUpper = true;
if (isdigit(password[i]))
hasDigit = true;
}
// Displaying the strength of password
cout << "Strength of password you have entered is ";
if (hasUpper && hasDigit && hasLower && (n >= 6)) // considering a strong must be of length 6 or more
cout << "strong" << endl;
else if ((hasLower || hasUpper) && hasDigit && (n >= 6))
//when at least a lower case or uppercase is used along with digit
cout << "moderate" << endl;
else
cout << "weak" << endl;
}
main.cpp
#include <iostream>
#include <fstream>
#include "data.h"
using namespace std;
int main(){
string e, p;
readEmail(e);
checkEmail();
return 0;
}
I have created this program with the knowledge of a couple of basic C++ courses I took a few semesters ago, and using online tutorials. This is not a homework or an assignment of any kind.
In your readEmail() function, the string email is a local variable. You passed the variable to the function by value, not by reference.
Also, if you pass it by reference, then there's no need to return anything (the function should be void).
void readEmail(string& email) //reads in the email id provided
{
cout << "Enter an email address: ";
cin >> email;
}
int main() {
string e, p;
readEmail(e);
checkEmail();
return 0;
}
But if you want to return the value, than there's no need for parameter, but you need to give that return value to your variable.
string readEmail() //reads in the email id provided
{
cout << "Enter an email address: ";
cin >> email;
return email;
}
int main() {
string e = readEmail();
checkEmail();
return 0;
}
I have to write a program that allows the user to enter a multiline poem, pressing the enter key to create a new line in the poem. All lines of the poem need to be stored in a single string, and I'm not sure how to concatenate the "\n" to user input. Additionally, once the user is done with the poem, I'm not sure how to then move on and execute further code in the program.
Here is the code I have so far:
/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/
#include <string>
#include <iostream>
using namespace std;
void makePoem()
{
string user_input;
cout << "Enter a poem of your own creation, one line at a time.\n";
cout << "Type 'quit' to exit the program.\n\n";
cout << "Type your poem, pressing the enter key to create a new line.\n\n";
cin >> user_input;
if (user_input == "quit")
{
cout << "\nGoodbye! Have a great day.\n";
}
else
{
getline(cin, user_input);
}
}
int main()
{
makePoem();
return 0;
}
Apologies if this question is too vague or such. Thanks for the help.
You need to read the user's input in a loop, appending each line to your target string, eg:
/*
Poetry In Motion; Cortez Phenix
This program allows the user to make a poem, and the program contains a
poem game. The most notable features are loops controlled by the user.
*/
#include <string>
#include <iostream>
using namespace std;
void makePoem()
{
string poem;
string user_input;
cout << "Enter a poem of your own creation, one line at a time.\n";
cout << "Type 'quit' to exit the program.\n\n";
cout << "Type your poem, pressing the enter key to create a new line.\n\n";
while (getline(cin, user_input))
{
if (user_input == "quit")
break;
poem += user_input;
poem += '\n';
}
cout << "\nGoodbye! Have a great day.\n";
}
int main()
{
makePoem();
return 0;
}
This looks like a homework problem so I wont give you actual code but here are some clues :
You need a loop that keeps going until the user enters "quit"
You then simply add the user input to the user_input string using the += operator
To add a newline to a string you add "\n" ex : user_input += "\n";
How I'm I going to add another condition in case the user didn't put anything in both username and password? ( "Empty Username and/or Password - Username and Password required!. Try Again? (Y/N)" )
here's my. code.
#include "stdafx.h"
#include <iostream>;
#include <string>;
using namespace std;
string username;
string password;
string choice;
int main(int argc, const char * argv[])
{
do {
Username:
std::cout << "Enter Username: ";
std::cin >> username;
if (username != "Joven")
{
std::cout << "Invalid Username. Please try again.\n\n\n";
goto choice;
goto Username;
}
Password:
std::cout << "Enter Password: ";
std::cin >> password;
if (password != "Fabricante7188")
{
std::cout << "Invalid Password. Please try again.\n\n\n";
std::cout << "Do you want to try again? y/n \n\n";
cin >> choice;
goto Password;
}
else
{
std::cout << "Correct Username and Password - Log In Successfull.\n";
break;
choice:
std::cout << "Do you want to try again? y/n \n\n";
std::cin >> choice;
}
}while (choice != "y" && choice != "n");
if (choice != "y" && choice != "n")
{
cout << "Invalid choice.\n";
goto choice;
}
system("pause");
return 0;
}`
thanks a lot!
Using the input operation >> you can't. It will block until there is some actual non-space input followed by the Enter key (or there's an error or "end of file").
The C++ standard solution (without resorting to OS specific functionality) is to read a whole like using e.g. std::getline, strip the input of leading (and possibly trailing) spaces, and then see if the resulting string is empty or not.
My solution would be something like this: (Edited by scorch 2017/01/14 10:24 AEST)
//#include "stdafx.h" I made this a comment because I don't appear to have this file. It wasn't necessary for me. Don't know whether you need it or not.
// include statements must not end with semicolons.
#include <iostream>
#include <string>
#include <cstdlib> // Has system() function
using namespace std;
int main(int argc, const char * argv[])
{
// Always declare variables inside the function.
string username;
string password;
string choice;
bool finished = false; // Declare this.
bool askingToTryAgain = false; // For when the user is asked whether they want to try again.
do {
std::cout << "Enter Username: ";
std::getline(std::cin, username);
std::cout << "Enter Password: ";
std::getline(std::cin, password);
// Validate username and password.
if (username != "Joven" && password != "Fabricante7188") {
// If both the username and password are invalid, report it.
std::cout << "Invalid Username and Password. Try again? (y/n): ";
} else if (username == "Joven" && password == "Fabricante7188") {
// If both fields are valid, login is successful.
std::cout << "Correct Username and Password - Log In Successful.\n";
finished = true; // Login is now complete, the loop will end.
} else {
// If just one of the fields is invalid, report which one it is.
if (username != "Joven") {
std::cout << "Invalid Username. Try again? (y/n): ";
}
if (password != "Fabricante7188") {
std::cout << "Invalid Password. Try again? (y/n): ";
}
}
if (finished == false) {
// If the login was unsuccessful, await user input for whether they wish to try again or not.
askingToTryAgain = true;
do {
// Fetch user input (y/n)
std::getline(std::cin, choice);
// Validate it.
if (choice != "y" && choice != "n") {
std::cout << "Enter 'y' or 'n'\n";
} else {
askingToTryAgain = false;
if (choice == "y") {
// Nothing to do here. The parent loop will continue after this one stops.
} else if (choice == "n") {
finished = true; // The user wishes to quit.
}
}
} while (askingToTryAgain);
}
} while (finished == false);
system("pause"); // During testing I used 'sleep 4' (sleep for 4 seconds) because I'm running Linux.
return 0;
}
Also, please do yourself a favour and avoid using 'goto' as a way to control the flow of program execution. Loops and conditions are a far better solution in a structured programming language such as C++ than the 'goto' statements.
I suggest you have a look at http://cplusplus.com/ as a good reference tool.
Hope this helps.
In c++, is it possible for me to make a loop, that asks the user to input information, and loop back to ask if they would like to keep adding information, until they dont. And store the values they typed into different parts of an array?
Ive been trying to use a while loop, but what happens is it will prompt if they want to add info, they select yes, they add it, if no, it puts into the terminal what they typed, but if I do yes twice, I just overwrite the first value, any way to correct this? I am quite new to programming and would appreciate any help, thank yo. (What I have is just a template to go off of, I know why it doesnt work, I also left out the preprocessor directives
#include <iostream>
#include <string>
using namespace std;
int main()
{
string add;
string name [100];
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name);
}
else if( add == "no" or add == "No")
{break;}
else
{
cout <<"sorry, that is not a valid response"<<endl<<endl;
}
}
cout<<name;
return 0;
}
I think trying to use pointers could work, but they have been confusing me haha. Any help or advice would be greatly appreciated, thank you.
Use of std::vector can make your life easier here. See a code snippet:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string add;
string name;
vector<string> names;
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name);
names.push_back(name);
}
else if( add == "no" or add == "No")
{
break;
}
else
{
cout <<"sorry, that is not a valid response"<<endl <<endl;
}
}
// printing contents
for(auto n:names)
cout << *n <<endl;
return 0;
}
Use array Name with Index instead of variable name when store information like this
#include <iostream>
#include <string>
using namespace std;
int main()
{
string add;
string name [100];
int index = 0; //Index Location of Array
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name[index]); // write name with index to insert value in particular index
}
else if( add == "no" or add == "No")
{break;}
else
{
cout <<"sorry, that is not a valid response"<<endl<<endl;
}
}
//loop here to output all value of name as mention above
cout<<name;
return 0;
}
I am learning file handling in C++. Just for a test I have written this small code. Basically what I want to do is make a user account program using file handling. So I want to use if else or while in my program to compare the data in the file.
For instance if a user enters his username as "john" the program should be able to search for the name john in the file and if it exists, it should allow the user to sign in and same with the password.
The code I have written is just a file writing test. Please help me out with the actual code. I am a beginner so sorry if it is too silly.
Thank you!
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<fstream>
#include<string.h>
using namespace std;
void main () {
ofstream file;
file.open("C:\tests1.txt", ios::trunc);
char name[50];
cout<<"\nEnter your name: ";
cin>>name;
file<<"Username: "<<name;
file.close();
cout<<"Thank you! Your name is now in the file";
ifstream file("tests1.txt");
if(file=="Username: Chinmay") {
cout<<"If else successfull\n";
} else {
cout<<"If else failed\n";
}
_getch();
}
Guys please help me out!!
Here is my two solutions and they are quite simple and rough. You may need to improve. Hope this may get you started.
If you have only small number of users and you need to check user account frequently, you may read in all the username and password, and store them in a std::map, where the key is username and the value is password.
Suppose that the username and password are stored in the file as below (separated by space):
user1 password1 user2 password2
You may implement the above idea like:
ifstream fin;
fin.open("input.txt");
map<string, string> m;
while(!fin.eof())
{
string username, password;
fin >> username >> password;
m[username] = password; // store in a map
}
fin.close();
// check account from user input
string user, pwd;
cin >> user >> pwd;
if (m.find(user) != m.end())
if (m[user] == pwd)
// login
else
// wrong password
else
// reject
If the number of users are quite large, you may read in the username and password one by one, and check account immediately.
while(!fin.eof())
{
string username, password;
fin >> username >> password;
if (username == user)
{
if (password == pwd)
// login
else
// wrong password
break;
}
}
// didn't find user and reject
#include<iostream>
#include<conio.h>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
int main() {
string name = "";
string line = "";
fstream f;
f.open("a.txt");
cout<<"Enter name"<<endl;
cin>>name;
if (f.is_open())
{
while (f.good() )
{
getline(f,line);
if(line==name)
{
cout<<"You can log in";
//Or do whatever you please in here after the username is found in the file
}
}
f.close();
}
else
{
cout << "Unable to open file";
}
getch();
return 0;
}