First input prompt skipped, while the rest are fine - if-statement

Here's the code in question. When I run the program, if I enter any number of users, the ability to enter the username of the first user is skipped, while I can enter the username of the rest and the code performs as expected.
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
cout << "We would be more than happy to set up an account for you." << endl;
cout << "You may set up to four users, how many would you like to set up?" << endl;
int new_users;
cin >> new_users;
if(new_users < 1 || new_users > 4)
{
cout << "Invalid number, please try again." << endl;
return 0;
}
int user_number = 1;
string user_name_1, user_name_2, user_name_3, user_name_4;
string password_1, password_2, password_3, password_4;
if(new_users == 4)
{
cout << "Please enter the name of user #" << user_number << ": " << endl;
getline (cin, user_name_1, '\n');
cout << "Please enter the password for user: " << user_name_1 << endl;
getline(cin, password_1);
user_number++;
new_users--;
}
if(new_users == 3)
{
cout << "Please enter the name of user #" << user_number << ": " << endl;
getline(cin, user_name_2, '\n');
user_number++;
new_users--;
cout << "Please enter the password for user: " << user_name_2 << endl;
getline(cin, password_2);
}
if(new_users == 2)
{
cout << "Please enter the name of user #" << user_number << ": " << endl;
getline(cin, user_name_3, '\n');
user_number++;
new_users--;
cout << "Please enter the password for user: " << user_name_3 << endl;
getline(cin, password_3);
}
if(new_users == 1)
{
cout << "Please enter the name of user #" << user_number << ": " << endl;
getline(cin, user_name_4, '\n');
user_number++;
new_users--;
cout << "Please enter the password for user: " << user_name_4 << endl;
getline(cin, password_4);
}
cout << "Thank you for setting up an account. Please login." << endl;
cout << "Enter user name: ";
string user, password_attempt;
getline(cin, user);
cout << "Enter password: ";
getline(cin, password_attempt);
if (user == user_name_1 && password_attempt == password_1)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_2 && password_attempt == password_2)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_3 && password_attempt == password_3)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_4 && password_attempt == password_4)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else
{
cout <<"User name or password is invalid, please try again." << endl;
}
cout << "Enter user name: ";
getline(cin, user);
cout << "Enter password: ";
getline(cin, password_attempt);
if (user == user_name_1 && password_attempt == password_1)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_2 && password_attempt == password_2)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_3 && password_attempt == password_3)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else if (user == user_name_4 && password_attempt == password_4)
{
cout << "login successful, welcome user: " << user << endl;
return 0;
}
else
{
cout << "Invalid user. Goodbye." << endl;
return 0;
}
}
/*Things it needs to do
. Take multiple user names
. Set password for each user name
. User able to "login"
. Prompt if user fails to login to login again.
OoO
Ask how many users it would like to set up, up to 4.
Take a user name
set the password for recently taken user name
If the user wishes to exit allow them to; if not repeat, we'll say up to 3 times.
Once all users are entered, they can login.
If the login fails they are offered another attempt.
*/
I've tried a different compiler and it still is showing up. I expected the first user to behave like the rest, not sure what's wrong.

Related

C++ ifstream is reading last line only

I am working on a program that allows a user to register an account. When a user registers for an account, the username and password are output to a text file "database.txt".
There is also an option for a user to search for their password by inputing their username if they forget their password. I find that this works fine when there is only one user registered in the .txt file database. However, when there is more than one user, the forgot password function returns the password of the most recent registered user, no matter which username is searched.
database.txt looks like this:
user1 111
user2 222
user3 333
No matter which user is entered to find the password, the function will always return 333, which is the most recent registered user's password. How do I fix this so that whichever user is searched, their password will output?
Here is the function:
void forgot()
{
int ch;
system("cls");
cout << "Forgotten? We're here to help." << endl;
cout << "Choose one of the options below: " << endl;
cout << "1. Forgot my password" << endl;
cout << "2. Forgot my username" << endl;
cout << endl;
cout << "Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1: // search for username to find password
{
int count = 0;
string searchUser, su, sp;
cout << "Enter your username: ";
cin >> searchUser;
ifstream searchUserName("database.txt");
while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
}
}
searchUserName.close();
if(count == 1)
{
cout << "Account found!" << endl;
cout << "Your password is: " << sp;
cin.get();
cin.get();
system("cls");
menu();
}
else
{
cout << "Sorry, that user ID does not exist." << endl;
cout << "Please contact our service team for more details." << endl;
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
case 2: // search for password to find username
{
int count = 0;
string searchPass, su2, sp2;
cout << "Enter your password: ";
cin >> searchPass;
ifstream searchPassword("database.txt");
while(searchPassword >> su2 >> sp2)
{
if(sp2 == searchPass)
{
count = 1;
}
}
searchPassword.close();
if(count == 1)
{
cout << "Your password has been found." << endl;
cout << "Your username is: " << su2;
cin.get();
cin.get();
system("cls");
menu();
}
else
{
cout << "Sorry, we couldn't find your password in our database." << endl;
cout << "Please contact our team for more information." << endl;
cin.get();
cin.get();
system("cls");
menu();
}
break;
}
default:
cout << "Invalid choice, please try again." << endl;
system("cls");
forgot();
}
}
You should break out of the while loop once you have found the user name here:
while(searchUserName >> su >> sp)
{
if(su == searchUser)
{
count = 1;
break; // add this
}
}
Now it will continue to overwrite a previously found user name until searchUserName >> su >> sp is no longer true which is once it encounters EOF in most cases.
The other part of the program has the same problem.
Personnally I would rewrite the code such that the condition whether a matching password has been found or not is part of the loop condition.

(C++) Read username and password from a file output problem

my program of registration and login encountered a few problems during output :
I have to register a new user and pass first(even if i alrd have previous usernames and passwords stored in the text file im trying to retrieve it from), after that only i can login using previous username and passwords and this repeats after i close the debug window and start debugging again (if i directly choose to login upon running the program, it will output "invalid username or password")
when logging out from a newly registered username, the program jumps to the
int main() AND DISPLAY "1. Register...."
but logging out from previous usernames, it jumps to
void login() and display "Username:"
*note: the last function isn't complete yet but i think it doesn't affect it (?) (the program worked fine before i added the void accountPage()tho)
*i am not supposed to use pointers plus i'm very new to c++
the code is a bit long but its just a lot of simple functions, i would rly appreciate it if someone can point out my mistake anywhere
#include <iomanip>
#include <cctype>
#include <fstream>
#include <string>
using namespace std;
//Global Variables
int Choice1;
int mobile, ic;
string user, pass, name, inUser, inPass;
//Function Prototypes
void register_user();
void login();
void bookRoom();
bool CheckCredentials(string, string);
void accountPage();
int main()
{
cout << "Welcome to Cozy Homes!\n";
cout << "Operating hours: 11am - 10pm Tuesday - Sunday\n\n\n\n";
do {
cout << "\n1. Register\n";
cout << "2. Log In\n";
cout << "3. Exit\n";
cout << "Please enter a number:";
cin >> Choice1;
if (Choice1 == 1)
{
register_user();
}
else if (Choice1 == 2)
{
login();
}
else if (Choice1 == 3)
{
cout << "Exiting now...\n";
return 0;
}
else if (Choice1 < 1 || Choice1 > 3)
{
cout << "Please choose a number from the menu!" << endl;
}
} while (Choice1 != 3);
system("pause");
return 0;
}
//Register page
void register_user()
{
cin.ignore();
cout << "\n\n\n" << "New Username: ";
getline(cin, user);
cout << endl;
cout << "New Password: ";
getline(cin, pass);
cout << endl;
cout << "Full name: ";
getline(cin, name);
cout << endl;
cout << "Mobile Number: ";
cin >> mobile;
cout << endl;
cout << "Ic Number (without \" - \"): ";
cin >> ic;
cout << endl;
cout << "Registered Successfully!" << endl;
cout << endl;
//Store username and password in login file
ofstream l("login.txt", ios::app);
if (!l.is_open()) {
cout << "could not open file \n";
}
l << user << " " << pass << endl;
l << endl;
l.close();
//Store other details in customer file
ofstream c("customer.txt", ios::app);
if (!c.is_open()) {
cout << "could not open file \n";
}
c << user << endl;
c << pass << endl;
c << name << endl;
c << mobile << endl;
c << ic << endl;
c << '\n';
c.close();
}
//Log in page
void login()
{
do
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
} while (CheckCredentials(inUser, inPass) != true);
}
//Validate their username and password
bool CheckCredentials(string inUser, string inPass)
{
string u;
string p;
bool status = false;
ifstream f;
f.open("login.txt");
if (!f.is_open())
{
cout << "Unable to open file!\n";
}
else if (f)
{
while (!f.eof())
{
f >> u >> p;
if (inUser == u && inPass == p)
{
status = true;
}
else
{
status = false;
}
}
}
f.close();
return status;
}
//Account Page
void accountPage()
{
int Choice2;
do
{
cout << "1. Profile\n";
cout << "2. Book a Room\n";
cout << "3. Cancel Booking\n";
cout << "4. Logout\n";
cout << "Please enter a number: ";
cin >> Choice2;
if (Choice2 == 1)
{
}
else if (Choice2 == 2)
{
}
else if (Choice2 == 3)
{
}
else if (Choice2 == 4)
{
cout << "Logging out.....\n\n\n\n";
cout << endl;
}
} while (Choice2 != 4);
}
//Booking page
void bookRoom() {
cout << " ";
}
```
Like this :
void login()
{
bool loggedin = false;
while(!loggedin)
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
loggedin = true;
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
}
}
or like this:
void login()
{
bool loggedin = false;
do
{
cout << "\nUsername: ";
cin >> inUser;
cout << "Password: ";
cin >> inPass;
if (CheckCredentials(inUser, inPass) == true)
{
loggedin = true;
cout << "\nLogin sucessful!" << endl;
cout << "Welcome, " << inUser << endl;
cout << endl;
accountPage(); // Redirects user to their account page after successfully logged in
}
else
cout << "\nInvalid username or password. " << endl;
}
while(!loggedin)
}
As this is a school assignment I did not bother to test the code myself.
It is just meant to get you futher and I did only minimal changes.
The point of your error is that the faulty function calls checkcredentials before a user and pasword is entered in the system.
If this solves your problem please mark as solution.
l << user << " " << pass << endl;
l << endl; <---- creates an empty line in your file. Is this intentional ?
l.close();
Clearly there is more bugs in your program. But this will get you further.
Have to do my own job now ;-)

Infinite loop in my program

Ok, so for my school project we are basically making a menu with 20 max people to enter information and change if need be. Everything was working fine. However, our assignment has us check input for zip code and Account Balance for integer values. I used a do-while loop for ZipCode validation until a positive number and a digit was entered. However, I get an infinite loop that I can't seem to fix. Here is my code. The error lies on lines 57-68 if you put into a compiler. Every time I enter a letter instead of a integer, I get an infinite loop. But I can't figure out why. Thanks!
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
struct Account //Structure to be used throughout
{
string CustomerName;
string CustomerAddress;
string City;
string State;
int ZIPCode;
string Telephone;
int AccountBalance;
string DateOfLastPayment;
};
//function prototypes
void valueChangeFunc(string, Account[], int);//This function will be used in option 2 for editing a certain customer information
int main()
{
Account array[20]; //Array to hold up to 20 customers
int choice; //this will hold which option the user decides to make 1-4
bool flagZip = false; //This will be used later on as a flag for a do-while loop
bool flag = false; //This will be used as a flag for the do-while loop right now
int index = 0; //Index for our customers. This tells how many customers have been entered
do //This do while loop will continue to ask the user what option to do until array fills up with 20 people and 4 is not entered
{
cout << "1. Enter new account information \n" <<endl
<< "2. Change account information \n" << endl
<< "3. Display all account information\n" <<endl
<< "4. Exit the program \n" <<endl;
cin >> choice;
if (choice > 4 || choice <= 0)//If user enters a number bigger than 4 or less then or equal to 0. Error!
cout << "Please enter a number between 1 and 4" << endl;
else if(choice == 1)
{
cout << "CustomerName: ";
cin.ignore();
getline(cin, array[index].CustomerName);
cout << "CustomerAddress ";
getline(cin, array[index].CustomerAddress);
cout << "City: ";
getline(cin, array[index].City);
cout << "State: ";
getline(cin, array[index].State);
do
{
cout << "Zip Code: ";
cin >> array[index].ZIPCode;
cin.ignore();
if (!isdigit(array[index].ZIPCode) && array[index].ZIPCode <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "Telephone: ";
getline(cin, array[index].Telephone);
flagZip = false;
do
{
cout << "AccountBalance: ";
cin >> array[index].AccountBalance;
cin.ignore();
if (array[index].AccountBalance <= 0)
cout << "Please enter a valid entry " << endl;
else
flagZip = true;
}while(flagZip == false);
cout << "DateOfLastPayment: ";
getline(cin, array[index].DateOfLastPayment);
cout << "\n\nCustomerName: " << array[index].CustomerName << endl;
cout << "CustomerAddress " << array[index].CustomerAddress <<endl;
cout << "City: " << array[index].City << endl;
cout << "State: " << array[index].State << endl;
cout << "Zip Code: " << array[index].ZIPCode << endl;
cout << "Telephone: " << array[index].Telephone <<endl;
cout << "AccountBalance: " << array[index].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[index].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
index++;
}
else if(choice == 2 && index != 0)
{
int num;
string valueChange;
do
{
cout << " Customer number: ";
cin >> num;
if (num > (index-1) || num < 0)
cout << " There is no customer with that number " << endl;
}while (num > (index-1));
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl;
cout << "You have requested information for customer number " << num << endl << endl;
cout << "What value do you want to change? (press 4 to change 'Date of last payment') \n";
cin.ignore();
getline(cin,valueChange);
valueChangeFunc(valueChange, array, num);
cout << "\nHere is the new value you entered for " << valueChange << endl;
cout << "\n\nCustomer Name: " << array[num].CustomerName << endl;
cout << "Customer Address " << array[num].CustomerAddress <<endl;
cout << "City: " << array[num].City << endl;
cout << "State: " << array[num].State << endl;
cout << "ZIPCode: " << array[num].ZIPCode << endl;
cout << "Telephone: " << array[num].Telephone <<endl;
cout << "Account Balance: " << array[num].AccountBalance << endl;
cout << "Date of last payment: " << array[num].DateOfLastPayment << endl << endl;
}
else if(choice == 3 && index != 0)
{
int num2;
do
{
cout << "Enter the Customer Number to display information regarding that customer" << endl;
cin >> num2;
if (num2 > (index-1) || num2 < 0)
cout << "That Customer does not exist " <<endl;
}
while(num2 > (index-1));
cout << "\n\nCustomerName: " << array[num2].CustomerName << endl;
cout << "CustomerAddress " << array[num2].CustomerAddress <<endl;
cout << "City: " << array[num2].City << endl;
cout << "State: " << array[num2].State << endl;
cout << "Zip Code: " << array[num2].ZIPCode << endl;
cout << "Telephone: " << array[num2].Telephone <<endl;
cout << "AccountBalance: " << array[num2].AccountBalance << endl;
cout << "DateOfLastPayment: " << array[num2].DateOfLastPayment << endl;
cout << "You have entered information for customer number " << index << endl << endl;
}
else
flag = true;
}while (flag == false);
return 0;
}
void valueChangeFunc(string valueChange2, Account array[], int num)
{
if (valueChange2 == "Customer Name" || valueChange2 == "Customer name" || valueChange2 == "customer Name" || valueChange2 == "customer name")
{
cout << "\nEnter new value for Customer Name: " <<endl;
getline(cin, array[num].CustomerName);
}
if (valueChange2 == "Customer Address" || valueChange2 == "Customer address" || valueChange2 == "customer Address" || valueChange2 == "customer address")
{
cout << "\nEnter new value for Customer Address: " <<endl;
getline(cin, array[num].CustomerAddress);
}
else if(valueChange2 == "city" || valueChange2 == "City")
{
cout << "\nEnter new value for City: " << endl;
getline(cin, array[num].City);
}
else if(valueChange2 == "state" || valueChange2 == "State")
{
cout << "Enter a value for State: " << endl;
getline(cin,array[num].State);
}
else if(valueChange2 == "Zip Code" || valueChange2 == "zip Code" || valueChange2 == "Zip code" || valueChange2 == "zip code")
{
cout << "\nEnter a value for Zip Code: " << endl;
cin >> array[num].ZIPCode;
}
else if(valueChange2 == "telephone" || valueChange2 == "Telephone")
{
cout << "\nEnter a value for Telephone: " << endl;
getline(cin, array[num].Telephone);
}
else if(valueChange2 == "Account Balance" || valueChange2 == "Account balance" || valueChange2 == "account Balance" || valueChange2 == "account balance")
{
cout << "\nEnter a value for account balance: " << endl;
cin >> array[num].AccountBalance;
}
else if(valueChange2 == "4")
{
cout << "\nEnter the value for Date of last payment: " << endl;
getline(cin, array[num].DateOfLastPayment);
}
else
cout << "Not entered correctly. Please enter a valid entry to edit " << endl;
}
Again everything worked until I started to use a loop to check for digit value of ZipCode. The loop only goes infinite when I enter a letter. It works for a negative number and positive number.
Short answer can be found in cplusplus.com (read the third paragraph)
Long answer:
This error isn't about ZipCode only, you can generate the same error when you input a letter instead of a number at the very first cin call.
cin is not type-safe so using a wrong type as an input results in an undefined behaviour (like the infinite loop you were experiencing) and that is why cin is a bit prone to errors. Also, cin gets the input value, however it doesn't remove newline, reading to a bit dirtier input from what you'd get with other methods.
Speaking of other methods, as explained in the link, try to use getline() whenever it is possible. You can use that function to get what cin buffer contains as a string and do additional type-check if necessary. Bug-free programs are more important than shorter programs.
As a personal note: try to use while loops instead of do..while ones when you can. That is not a general rule of programming but it looks more readable and is easier to understand in general (IMHO).
Also, try to use functions to split your program into parts. For example, the cout blocks where you are just printing the information stored to the screen can be turned into a function. You're using the same cout structure (it would shorten your code by 4 * 9 lines).
Finally, if you're using an integer as a key value to separate algorithms, try to use switch...case instead of if-else blocks. (Again, just my opinion).

Issues figuring out readin/writeout for a bank program

I am trying to make a banking program that can read a username and password from a text file, and compare it to what the user enters. I have searched and tried a few different methods but I can't seem to get it to work. Im sorry if this is a re-post I just can't figure it out.
I am very new to coding so please forgive my mistakes.
The text file I have is called : "Account.txt"
It contains "username" on the first line then "userpassword" on the second line.
/*
Hunter Walker 11/10/2015
Banking Application with Input validation
Assignment 2
*/
//Headers
#include<iostream>
#include<string>
#include<cstdlib>
#include <fstream>
using namespace std;
//Variables
char input1, input2;
string username,userpassword, newusername, newuserpassword;
string customuser, custompass;
double amountin, amountout;
double total = 0;
//Function declarations
int bankingmenu();
int newaccount();
int login();
int main();
int mainmenu();
int deposit();
int withdraw();
int showbalance();
//Code to read from file
// The main menu for the banking application
int mainmenu()
{
cout << "Hi! Welcome to Future Computer Programmer ATM Machine!" << endl;
cout << "Please select an option from the menu below:" << endl;
cout << "l -> Login " << endl;
cout << "c -> Create New Account " << endl;
cout << "q -> Quit " << endl;
cin >> input1;
return 0;
}
// Function to allow the user to make a new account
int newaccount()
{
cout << "**********************************" << endl;
cout << "Welcome to the create an account menu!" << endl;
cout << "Please enter your desired username:" << endl;
cin >> newusername;
cout << "Please enter a password for your account:" << endl;
cin >> newuserpassword;
cout << "Thank you for creating an account with Future Computer Programmer ATM Machine!" << endl;
cout << "Your username is " << newusername << " and your password is " << newuserpassword << "." << endl;
cout << endl;
cout << "Reminder: Don't share your username or password with anyone." << endl;
cout << endl;
cout << "**********************************" << endl;
}
// Function to allow user to login to their account
int login()
{
cout << "Please enter username:" << endl;
cin >> username;
cout << "Please enter password:" << endl;
cin >> userpassword;
ifstream inputFile;
inputFile.open("Account.txt");
cout << customuser << " " << custompass << endl;
if (customuser == username && custompass == userpassword)
{
bankingmenu();
}
else
{
cout << "User name or password incorrect!" << endl;
cout << "Returning to main menu!" << endl;
return main();
}
inputFile.close();
return 0;
}
// The secondary menu for withdrawing/depositing/ or checking balance
int bankingmenu()
{
cout << "*******************************" << endl;
cout << "Please select an option from the menu below::" << endl;
cout << " d -> Deposit Money" << endl;
cout << " w -> Withdraw Money" << endl;
cout << " r -> Request Balance" << endl;
cout << " q -> Quit" << endl;
cin >> input2;
if (input2 == 'd')
{
deposit();
}
else if (input2 == 'w')
{
withdraw();
}
else if (input2 == 'r')
{
showbalance();
}
else if (input2 == 'q')
{
cout << "Returning to main menu! " << endl;
return main();
}
else
{
cout << "Please select a valid input and try again!" << endl;
return bankingmenu();
}
return 0;
}
// Function to allow to deposit to account
int deposit()
{
cout << "Please enter the amount of money you wish to deposit:" << endl;
cin >> amountin;
total = amountin + total;
cout << "The deposit was a success! Thanks for using Future Computer Programmer ATM Machine!" << endl;
return bankingmenu();
}
// Function to allow user to withdraw from account
int withdraw()
{
cout << "Please enter the amount you would like to withdraw:" << endl;
cin >> amountout;
if (total < amountout)
{
cout << "You can't withdraw more money than you have!" << endl;
cout << "Please select a different amount to withdraw." << endl;
return withdraw();
}
else
{
cout << "The amount has been withdrawn." << endl;
total = total - amountout;
return bankingmenu();
}
}
// Function to display the balance
int showbalance()
{
cout << "The balance in your account is $" << total << "." << endl;
return bankingmenu();
}
// The main function that calls all previous functions to run
int main()
{
mainmenu();
// Option to login
if (input1 == 'l')
{
login();
}
// Option to make a new account
else if (input1 == 'c')
{
newaccount();
}
// Option to exit program
else if (input1 == 'q')
{
cout << "Thanks for using the Future Computer Programmer ATM Machine! " << endl;
cout << "The program will now exit!" << endl;
return 0;
}
// Input validation
else
{
cout << "Please select a valid menu option and try again!" << endl;
return main();
}
return 0;
}
IN the newAccount function you will have to store the username and password with the following lines of code.
ofstream outfile;
outfile.open("Account.txt");
outfile<<newusername<<endl;
outfile<<newpassword<<endl;
outfile.close();
In your login function you will have to add the following two lines of code after you open the file 'Account.txt'
inputFile>>customuser;
inputFile>>custompass;
This would solve the present issue of getting the username and password of single user. But, you'll still have to figure out a way to get usernames and passwords for multiple users who'll use your application.
An easier adaptation to deal with multiple users would be to simply append username and password to the file and search for the username and password sequentially.
An alternative to the above approach is to use a database to store username and password.

How to read multiple text lines [duplicate]

This question already has answers here:
How to stop a while loop
(5 answers)
Closed 8 years ago.
In my text file ("UsernamePassword.txt"), there are multiple lines of Usernames and Passwords. When I tried logging in using the Username and Password on the 2nd line or 3rd line, it brings me to the "invalid username or password" part. Only the 1st line of username and password works.
Any suggestion on how to read the multiple lines?
{
fstream inFile;
string user, pass, username, password;
int choice;
Logo();
cout << endl << endl << endl;
inFile.open("UsernamePassword.txt");
if (!inFile)
cout << "Unable to Open File";
else
{
while (username != user)
cout << endl << endl << endl;
cout << " Please enter username: ";
cin >> user;
cout << " Please enter password: ";
cin >> pass;
{
inFile >> username >> password;
if (user == username && pass == password)
{
system("cls");
cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl;
cout << "\t ****************************************** " << endl;
cout << "\t ** !!! Welcome to CherryLunch !!! ** " << endl;
cout << "\t ****************************************** " << endl;
cout<<endl<<endl<<endl<<endl<<endl;
system("pause");
system("cls");
MainMenu();
}
else
{
cout<<endl<<endl<<endl<<endl<<endl;
cout << "\t !!! Invalid Username or Password !!!" << endl<<endl;
cout << "\t *** Please try again ***" << endl;
cout<<endl<<endl<<endl<<endl<<endl;
system("pause");
system("cls");
}
}
}
inFile.close();
}
You haven't given us the whole code - but I have placed comments in your code (various places) to indicate whether you wanted to do this willingly or did it by mistake:
{
fstream inFile;
string user, pass, username, password;
int choice;
Logo();
cout << endl << endl << endl;
inFile.open("UsernamePassword.txt");
if (!inFile)
cout << "Unable to Open File";
else
{
while (username != user) // Only the following run will repeat ( if this is the intention?)
cout << endl << endl << endl;
cout << " Please enter username: ";
cin >> user;
cout << " Please enter password: ";
cin >> pass;
{ // This is scoped operation
inFile >> username >> password;
if (user == username && pass == password)
{
system("cls");
cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl;
cout << "\t ****************************************** " << endl;
cout << "\t ** !!! Welcome to CherryLunch !!! ** " << endl;
cout << "\t ****************************************** " << endl;
cout<<endl<<endl<<endl<<endl<<endl;
system("pause");
system("cls");
MainMenu();
}
else
{
cout<<endl<<endl<<endl<<endl<<endl;
cout << "\t !!! Invalid Username or Password !!!" << endl<<endl;
cout << "\t *** Please try again ***" << endl;
cout<<endl<<endl<<endl<<endl<<endl;
system("pause");
system("cls");
} // End of inner else
} // This is the end of scoped operation
} // End of Outer else
inFile.close();