How to make seperate menus that work based on the login - c++

So for the program I am making, I wanted to make a login that goes to two different menus then go back to the login. I'm not sure how to approach it now.
It goes something like:
string User;
string Pass;
int Option;
void Login(){
cout << "Enter your username: ";
cin >> User;
cout << "Enter your password: ";
cin >> Pass;
}
void Admin(){
system("CLS");
cout << "Welcome Admin" << endl;
cout << "------------" << endl;
cout << "1. Do something" << endl;
cout << "2. Do something else" << endl;
cout << "3. Log out" << endl;
cout << "4. Quit Program" endl;
cin >> Option;
}
void User(){
system("CLS");
cout << "Welcome User" << endl;
cout << "------------" << endl;
cout << "1. Do another thing" << endl;
cout << "2. Do something other things don't do" << endl;
cout << "3. Log out" << endl;
cout << "4. Quit Program" endl;
cin >> Option;
}
int main(){
Login();
if(User == "admin" && Pass == "admin"){
Admin();
if(Option == 3){
// What should I add here if would want to return to login then to user menu
}
}
else
User();
}

Well, if you want to return to login menu you can use a loop:
int main()
{
while(1)
{
Login();
if(User == "admin" && Pass == "admin")
{
Admin();
}
else
{
User();
}
if(Option == 3) continue;
if(Option == 4) break;
}
return 0;
}
upd: sorry, forgot about the loop :)

Related

How can I return user to original switch menu from do-while loop?

how can I get user to go back to original switch menu once the user selects N at the end. When user selects N, would I use another loop to get them back to original menu? Any help is greatly appreciated.
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please enter an option" << endl;
int option;
cin >> option;
switch(option)
{
case 1:
{
char again;
do
{
/* code
*/
cout << "Would you like to play again? Y/N" << endl;
cin >> again;
}while(towlower(again) == 'y'); // I'm not sure whether to use another do-while loop.
When user selects N, would I use another loop to get them back to original menu?
Yes, one that is put around the original menu, eg:
bool keepRunning = true;
do {
cout << "Total Chips: " << chips << endl;
cout << "1) xxxxx" << endl;
cout << "2) xxx" << endl;
cout << "Please enter an option" << endl;
int option;
cin >> option;
switch (option)
{
case 1:
{
char again;
do
{
/* code
*/
cout << "Would you like to play again? Y/N" << endl;
cin >> again;
}
while (again == 'y' || again == 'Y');
break;
}
...
}
}
while (keepRunning);

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

Program Infinitely Looping

This is a snippet of the code from my program. The function getMenuChoice() runs successfully on Visual Studio when I enter integers but when I enter a character it goes into an infinite loop. I was told that my program does not have to account for the user entering a character but yet when I submit it, the grading machine tells me it "exceeded the allowed length". Besides the fact it does not account for characters, I am not sure what is wrong with the function. If I was to account for characters though, how would I do that?
// Calls header and menu.
int main() {
printHeading();
getMenuChoice();
}
//Prints the header.
void printHeading() {
cout << "*******************************" << endl
<< " Birthday Calculator " << endl
<< "*******************************" << endl << endl;
}
//Prints the closer.
void printCloser() {
cout << endl;
cout << "****************************************************" << endl
<< " Thanks for using the Birthday Calculator " << endl
<< "****************************************************" << endl
<< endl;
}
void printMenu() {
cout << endl << endl;
cout << "Menu Options" << endl
<< "------------" << endl;
cout << "1) Determine day of birth" << endl;
cout << "2) Print the next 10 leap years" << endl;
cout << "3) Determine birthdays for the next 10 years" << endl;
cout << "4) Finished" << endl << endl;
cout << "Choice --> ";
}
//Gets user's menu choice.
int getMenuChoice() {
int choice;
printMenu();
cin >> choice;
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
}
//Allows the user to enter another choice
//after they have executed one choice.
printMenu();
cin >> choice;
}
//Prints closer when user chooses 4.
printCloser();
return 0;
}
Its been awhile since I played with C++ but here is a shot.
int choice;
printMenu();
cin >> choice;
ValidateOption(choice);
// Then if you want them to be able to pick again you can just do it over again
printMenu();
cin >> choice;
ValidateOption(choice);
function ValidateOption(int choice){
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//Prints closer when user chooses 4.
else if (choice == 4){
printCloser();
return 0;
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
// Make the user select again because the input was invalid
printMenu();
cin >> choice;
}
}
}
You can try to flush cin like this:
cin >> choice;
cin.clear();
cin.ignore(INT_MAX);
or as suggested by #user4581301
cin.ignore(numeric_limits<streamsize>::max(), '\n');

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.

Struct error: Request for member

I am making a program with which to save banking information (i.e., account, password, balance). I am having trouble with a certain error but I'm not sure of the cause.
Here is the entire code.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int x = 0;
void addUser();
void login();
void deposit();
void withdrawl();
struct bankUser
{
double balance;
string account, password;
};
bankUser user[20];
int menu()
{
ofstream myfile("bankmachine.txt", ios::app);
char choice;
cout << "1) Add account" << endl;
cout << "2) Log in" << endl;
cout << "3) Make deposit" << endl;
cout << "4) Make withdrawl" << endl;
cout << "5) Quit" << endl << endl;
cout << "What would you like to do?: ";
cin >> choice;
cout << endl;
switch (choice)
{
case '1':
addUser();
break;
case '2':
login();
break;
case '3':
deposit();
break;
case '4':
withdrawl();
break;
case '5':
myfile << user[x].balance << endl;
myfile.close();
cout << "Thank you for using the banking system." << endl << endl;
system ("pause");
return 0;
break;
default:
cout << "That is not a valid option. Please choose again." << endl << endl;
menu();
}
}
void addUser()
{
if ((x >= 0) && (x < 20))
{
cout << "Please enter your desired account name: ";
cin >> user[x].account; // Account name.
cout << "Thank you, now please enter your desired password: ";
cin >> user[x].password; // Account password.
cout << "\nAccount created. You may now log in." << endl << endl;
ofstream myfile("bankmachine.txt", ios::app); // Opens the text file at the end of the file (if data is already present).
myfile << user[x].account << endl; // Writes to text file.
myfile << user[x].password << endl; // ^
myfile.close(); // Close text file (important).
x++; // Increases to simulate the addition of another user.
menu();
}
else // Will display if user has entered 20 users.
{
cout << "You have entered the maximum number of users." << endl;
menu();
}
}
void deposit()
{
int deposit;
string answer;
do
{
cout << "Please enter the amount of money that you would like to deposit: ";
cin >> deposit;
user[x].balance += deposit;
cout << "Thank you. Your new balance is " << user[x].balance << "." << endl << endl;
cout << "Would you like to make another deposit? (Y/N): ";
cin >> answer;
} while ((answer != "N") && (answer == "Y"));
cout << endl;
menu();
}
void withdrawl()
{
int withdraw;
string answer;
do
{
cout << "Please enter the amount of money that you would like to withdraw: ";
cin >> withdraw;
if (withdraw <= user[x].balance)
{
user[x].balance -= withdraw;
}
else
{
cout << "\nSorry, you do not have sufficient funds to complete this withdrawl.\nPlease try again." << endl << endl;
withdrawl();
}
cout << "Thank you. Your new balance is " << user[x].balance << "." << endl << endl;
cout << "Would you like to make another withdrawl? (Y/N): ";
cin >> answer;
} while (answer != "N" && answer == "Y");
cout << endl;
menu();
}
void login() // Function to log in.
{
string user, pw, usernameCheck, passwordCheck;
double balance;
cout << "Please enter your login information." << endl << endl;
cout << "Account name: ";
cin >> user;
cout << "Password: ";
cin >> pw;
cout << endl;
ifstream myfile("bankmachine.txt", ios::app);
while (!myfile.eof()) // Loops until end of file.
{
getline(myfile, usernameCheck);
if (usernameCheck == user)
{
getline(myfile, passwordCheck);
if (passwordCheck == pw)
{
myfile >> balance;
cout << "Login successful." << endl;
cout << "Your balance is " << balance << "." << endl << endl;
user[x].balance = balance;
}
else // If not, display:
{
cout << "Password incorrect." << endl << endl;
}
}
}
myfile.close(); // Close text file (important).
menu();
}
int main()
{
cout << "Welcome to the banking system." << endl << endl;
menu();
}
I keep getting this error (on line 172):
request for member 'balance' in 'user.std::basic_string<_CharT, _Traits,
_Alloc>::operator[] [with _CharT = char, _Traits = std::char_traits<char>, _Alloc =
std::allocator<char>](((unsigned int)x))', which is of non-class type 'char'|
What is this caused by? How can I fix it? Any answers are appreciated.
Judging by the error provided it seems as if user is not of type struct bankUser, but a std::string.
You are trying to assign a std::string (balance) to character at offset x of your std::string named user, which is doomed to fail.
TL;DR user is not declared to be a struct bankUser.