How to read multiple text lines [duplicate] - c++

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();

Related

Code skips 6 lines of code on its own, what could be wrong here?

I have a problem with my code, it skips 6 lines of code, and I don't know what the problem could be. I'm just practicing C++, making a bank app, and in the registration menu it skips 6 lines of code for some reason. I would appreciate any help or suggestion! The code can look a little dirty. I don't understand why the code skips the input for the cityAddress, stateAddress, zipAddress after I type the houseAddress input.
// Registration menu code
void registerMenu() {
bool registerSuccess = false;
bool usernameSuccess = false;
string saveInfo;
system("CLS"); // Clear Console
cout << "Please create your account.\n";
cout << "First Name: ";
cin >> firstName;
cout << "Last Name: ";
cin >> lastName;
cout << "Phone Number: ";
cin >> phoneNumber;
cout << "Address: ";
cin >> houseAddress;
cout << "City: ";
cin >> cityAddress;
cout << "State: ";
cin >> stateAddress;
cout << "Zip code: ";
cin >> zipAddress;
cout << "\n\n";
cout << "Save information?\nY/N\n";
cin >> saveInfo;
if (saveInfo == "Y") {
cout << "-----------INFORMATION SAVED!-----------\n";
}
else if (saveInfo == "N") {
registerMenu();
}
else {
registerMenu();
}
cout << "\n\n";
do {
cout << "Username: ";
cin >> username;
ifstream usernameCheck("user_" + username + ".txt");
if (usernameCheck.is_open()) {
cout << "This username already exists. Create a different username.\n\n";
Sleep(1000);
}
else {
cout << "\n\t! USERNAME AVAILABLE !\n";
usernameSuccess = true;
}
} while (!usernameSuccess);
do {
cout << "Password: ";
cin >> password;
if (password.length() >= 8) {
cout << "Initial deposit to your account: $";
cin >> balance;
system("CLS"); // Clear Console
cout << "Registration complete!\n";
// [START] Create Account file
ofstream registration;
registration.open("user_" + username + ".txt");
registration << username << endl << password << endl << balance;
registration.close();
// [FINISH] Create Username file
registerSuccess = true;
password = password;
Sleep(1000);
system("CLS"); // Clear Console
cout << "--------------------------------" << endl;
cout << " Account Information\n";
cout << "Username: " << username << endl;
cout << "Password: " << password << endl;
cout << "Balance: $" << balance << endl;
cout << "--------------------------------" << endl;
cout << "Forwarding you in 5 seconds..." << endl;
Sleep(5000);
mainMenu();
}
else {
cout << "\n\nPassword must contain at least 8 characters. (You entered " << password.length() << " characters)\nPlease try again.\n";
}
} while (!registerSuccess);
}
Home addresses usually have spaces in them. Cin reads up to the first delimiter which is a space. Instead, try
std::getline(cin, houseAddress)

(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 ;-)

Run Time Error When Program is Running C++

I am getting a runtime error when the program is running it takes the username but then when it comes for password it shows me: Debug Error Run Time Check Failure #3-T.
#include <iostream>
using namespace std;
int main()
{
int choice;
float username, password; //login
int name, age, gender, dob, address, workinfo;
cout << "Welcome To HDFC Bank" << endl;
//Menu Option
cout << "Choose an option: " << endl;
cout << "===========================" << endl;
cout << "1. Login" << endl;
cout << "2. Register" << endl;
cout << "===========================" << endl;
cin >> choice;
if (choice == 1) {
cout << "Please Enter Your Username: " << endl;
cin >> username;
cout << "Please Enter your Password: " << endl;
cin >> password;
if (choice == 1 || password = 2) {
cout << "Welcome To The Program!!!" << endl;
}
else {
cout << "Wrong Details!!" << endl;
}
}
else if (choice == 2) {
cout << "Enter Your Full Name: " << endl;
cin >> name;
cout << "Enter Your Age" << endl;
cin >> age;
cout << "Enter Your Date of Birth(dd/mm/yyyy): " << endl;
cin >> dob;
cout << "Enter Your Gender(M/F)" << endl;
cin >> gender;
cout << "Enter Your Address: " << endl;
cin >> address;
cout << "Enter Your Work Details: " << endl;
cin >> workinfo;
}
if (age < 21) {
cout << "Sorry You cannot Register as you are below 21 years. Please try later." << endl;
}
else {
cout << "You have succesfully registered. Please check your email." << endl;
}
return 0;
}
You should definitely learn more about Types and STL Streams.
But assuming you're experimenting here is little bit more meaningful version of your code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int choice = 0;
std::string username, password; //login
int age = 0;
std::string name, gender, dob, address, workinfo;
cout << "Welcome To HDFC Bank" << endl;
//Menu Option
cout << "Choose an option: " << endl;
cout << "===========================" << endl;
cout << "1. Login" << endl;
cout << "2. Register" << endl;
cout << "===========================" << endl;
cin >> choice;
cin.ignore();
if (choice == 1) {
cout << "Please Enter Your Username: " << endl;
getline(cin, username);
cout << "Please Enter your Password: " << endl;
getline(cin, password);
if (password == "1" || password == "2") {
cout << "Welcome To The Program!!!" << endl;
}
else {
cout << "Wrong Details!!" << endl;
return 0;
}
}
else if (choice == 2) {
cout << "Enter Your Full Name: " << endl;
getline(cin, name);
cout << "Enter Your Age: " << endl;
cin >> age;
cin.ignore();
cout << "Enter Your Date of Birth(dd/mm/yyyy): " << endl;
getline(cin, dob);
cout << "Enter Your Gender(M/F)" << endl;
getline(cin, gender);
cout << "Enter Your Address: " << endl;
getline(cin, address);
cout << "Enter Your Work Details: " << endl;
getline(cin, workinfo);
}
if (age < 21) {
cout << "Sorry You cannot Register as you are below 21 years. Please try later." << endl;
}
else {
cout << "You have successfully registered. Please check your email." << endl;
}
return 0;
}
Note that we use cin.ignore() after reading int as described here

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.

check username and password input with data stored in text file in c++

This is my code:
`
void Customer::validate_cust_username_and_password()
{
string uname, pword;
cout << "enter name: " << endl;
cin >> uname;
cout << "enter password: " << endl;
cin >> pword;
ifstream myfile("cust_username_and_password.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
if (uname == cust_username && pword == cust_password)
{
cout << "Login successfully." << endl;
cust_mainmenu();
break;
}
else
{
cout << "Wrong username or password!" << endl;
break;
}
}
myfile.close();
}
}
`
This is another code which store the username and password:
`void Customer::cust_register_name_and_password()
{
string un, pw;
ofstream myfile("cust_username_and_password.txt", ios::out | ios::app);
cout << "Enter Customer Username= " << endl;
getline(cin, un);
cout << "Enter Customer Password= " << endl;
getline(cin, pw);
myfile << endl << un << " " << pw << endl;
myfile.close();
cout << "Register Successfully." << endl;
system("pause");
}`
So the problem is when I enter the username and password which I already stored in the text file before, the output is only showing the "Wrong username or password!".
Really appreciate if anyone can help.
In your validate_cust_username_and_password function, you never read in the username and password. Add this:
myfile >> cust_username >> cust_password;
cust_username and cust_password are never set anywhere in this code, so they will never match the user's input (unless the user enters empty strings).
string uname, pword;
cout << "enter name: " << endl;
cin >> uname;
cout << "enter password: " << endl;
cin >> pword;
ifstream myfile("password.txt");
if (myfile.is_open())
{
while (!myfile.eof())
{
if (uname == "test" && pword == "0000")
{
cout << "Login successfully." << endl;
cust_mainmenu();
break;
}
else
{
cout << "Wrong username or password!" << endl;
break;
}
}
myfile.close();
}
}
Where did cust_username magically appear. Was Paul Daniels involved. Paul I take that back you are not as bad as David Blaine - but not a lot