Checking integer for input validation of a node - c++

I'm trying to do my input validation where I have already predefined data in my program. When I want the user to key in a new employee id, I want it to check whether that ID is already in the database, if yes, how do i keep looping it until the user types in an id which is not in the database?
struct employee {
int empNo, salary, performance;
string name, phoneNo, address, depNo, depName;
employee* next;
employee* previous;
} *temp, *head, *tail, *newhead, *newtail, *newnode;
void validate()
{
cout << "Input not accepted, please try again!" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
int main()
{
int choice = 1;
int num, salary, performance = 0;
string name, hpnum, depName, depNo, address;
bool execute = true;
insertemployeerecord(0002, "Ethan Tan", 16000, "017-2399193", "Kuala Lumpur, Malaysia", "F001", "Finance", 2);
insertemployeerecord(0003, "Nikshaen Kumar", 15000, "016-9188131", "Los Angeles, California", "A001", "Audit", 3);
insertemployeerecord(0001, "Koughen Mogan", 17500, "014-1233241", "Los Angeles, California", "F001", "Finance", 4);
while (execute)
{
cout << "..........................................................." << endl;
cout << " EMERGE EMPLOYEE SYSTEM " << endl;
cout << "..........................................................." << endl;
cout << endl;
cout << "1. Add an Employee Record" << endl;
cout << "2. Display All Records" << endl;
cout << "3. Search by Employee ID" << endl;
cout << "4. Search by Employee overall performance" << endl;
cout << "5. Sort and display by Employee ID in ascending order" << endl;
cout << "6. Sort and display by Employee Salary in ascending order " << endl;
cout << "7. Sort and display by Employee Overall Performance in ascending order " << endl;
cout << "8. Modify an Employee Record" << endl;
cout << "9. Delete an Employee Record" << endl;
cout << "10. Calculate salary package of an employee" << endl;
cout << "11. Exit" << endl;
cout << endl << endl;
cout << "Select your option: ";
cin >> choice;
if (choice == 1)
{
system("cls");
cout << "Enter employee number: ";
cin >> num;
while (!cin >> num) //to see if user types anything besides number
{
validate();
cout << "Enter employee number: ";
cin >> num;
}
temp = head;
bool verify = true;
if (temp != NULL)
{
while (temp->empNo != num)
{
temp = temp->next;
if (temp == NULL)
{
verify = false;
break;
}
}
while (verify == true) //if the user types an id that is found in the database
{
validate();
cout << "Employee found in database!" << endl;
cout << "Enter employee number: " << endl;
cin >> num;
}
if (verify == false)
{
cin.get();
}
}
cout << endl;
cout << "Enter employee name: ";
getline(cin, name);
As you can see, my output can detect if there is an alphabet being typed and also if the user types an id thats already in the database, but when I type a new id, example being 4, the system still says it detects from the database
Enter employee number: a
Input not accepted, please try again!
Enter employee number: 1
Input not accepted, please try again!
Employee found in database!
Enter employee number:
2
Input not accepted, please try again!
Employee found in database!
Enter employee number:
3
Input not accepted, please try again!
Employee found in database!
Enter employee number:
4
Input not accepted, please try again!
Employee found in database!

You can do something like this :
int enter_employee_number() {
int number;
do{
cout << "Enter employee number: ";
cin >> number;
bool fail = cin.fail();
if(fail)
cout << "Input not accepted, please try again!" << endl;
} while (fail);
return number;
}
string enter_employee_name() {
string name;
do{
cout << "Enter employee name: ";
cin >> name;
bool fail = cin.fail();
if(fail)
cout << "Input not accepted, please try again!" << endl;
} while (fail);
return name;
}
employee get_employee(int number) {
// retrieve your employee and return it.
}
int main() {
// other part of your code
if (choice == 1) {
system("cls");
while(true) {
int empNo = enter_employee_number();
employee emp = get_employee();
if (emp != nullptr) {
cout << "Employee found in database!" << endl;
string empName = enter_employee_name();
// call method that use empName
}
else {
cout << "Employee not found in database!" << endl;
}
cout << endl;
}
}
}

Recommended way of input validation is via getting everything in a string, like define string inputLine and use std::getline() and then parsing it using std::istringstream(inputLine). If you want to continue till validation succeeds, put below code in loop.
if ( stringStream >> ID >> std::ws && stringStream.get() == EOF)
//At this point you have Employee Id in ID variable , Now you can do database check.
if(validate(ID)) // if validation succeeds.
break; // Break out of loop, otherwise continue till you get correct input.

Related

How to display user account only using user ID num

Im basically making a database that stores a users account info. (Name, Phone number, ID, etc) I want to be able to display a specific persons info by entering in their ID num.
I have a struct with basic info and an array struct that stores each person and their info. I need to be able to type in a persons ID and have it display their info.
(I am still in first year of CS degree plz be gentle lol)
struct Account{
string name;
string city;
string state;
int ZIP;
int phone;
int IDNUM;
double ACT_BAL;
string LST_PMNT;};
Main fuction
const int SIZE = 20;
Account customers[SIZE];
const int NEW_INFO = 1, CHNG_INFO = 2, DISP = 3, EXIT = 4;
char choice1;
int choice;
int n;
int NEWCUST;
int results;
do
{ // menu display
cout << "Customer Database\n"
<< "----------------------------\n"
<< "1. Enter new account info\n"
<< "2. Change account info\n"
<< "3. Display all account info\n"
<< "4. Exit\n";
cin >> choice;
//respond to user input
switch (choice)
case NEW_INFO:
cout << "Would you like to enter a new cusomter?\n"
<< "(Y/N)";
cin >> choice1;
if (choice1 == 'Y' || choice1 == 'y')
{
cout << "How many new customers?" << endl; //User eneters in new customer info without having to enter in a full array worth of customers.
cin >> NEWCUST;
for (n = 0; n < NEWCUST; n++)
{
cout << "ID Number: ";
cin >> customers[n].IDNUM;
cout << "Enter in a name: ";
cin >> customers[n].name;
cout << "City: ";
cin >> customers[n].city;
cout << "State: ";
cin >> customers[n].state;
cout << "ZIP code: ";
cin >> customers[n].ZIP;
cout << "Phone number: ";
cin >> customers[n].phone;
cout << "Account Balance: ";
cin >> customers[n].ACT_BAL;
cout << "Lasy payment date: ";
cin >> customers[n].LST_PMNT;
}
}
break;
case CHNG_INFO: // Changes info
break; // displays all info (work in progress)
case DISP:
cout << "Enter customers ID number" << endl;
cin >> customers[].IDNUM;
results = linearSearch(customers, SIZE, customers[].IDNUM);
break;
case EXIT:
cout << "Cosing......" << endl; //exits progeam
break;
To get a specific user details, you can do the following:
Declaring num as short int to hold a simple User ID, you can change it. N = 50 as you've provided the constant. Now, unless the loop finds the inputted ID matching with one of the struct's idNum, it'll be executed 50 times (max).
cout << "Input account code: ";
cin >> num;
for (int i = 0; i < N; i++)
{
if (num == acc[i].idNum)
{
cout << "Name: " << acc[i].name << endl
<< "..." << endl;
}
}

How can I write a better and cleaner version of my bank account code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have this small bank account code to make an account and to access an already made account. It is pretty procedural but I need help knowing what to do to make it better. Like I want an option to loop back after deposit is made and withdraw is made and a separate key to exit the console application.
int main(){
//MIKE BANK LTD
string name;
string defacctNum = "123456";
string acctNum;
int defacctPin = 1357;
int acctPin;
double acctBal;
double defacctBal = 100.59;
int withdraw;
int deposit;
int check;
int yo;
cout << "|----------------------------------------------------------------------------------|" << endl;
cout << "|Hello customer, welcome to Obadan Bank. Do you already have an account with us?|" << endl;
cout << "|----------------------------------------------------------------------------------|" << endl;
cout << "|----------------------------------------------------------------------------------|" << endl;
cout << "|Enter 1 if you have an account or 2 if you want to create a new one.|" << endl;
cin >> check;
if (check == 1) {
cout << "Enter account number: ";
cin >> acctNum;
while (acctNum != defacctNum) {
cout << "Wrong account number not recognized try again: ";
cin >> acctNum;
}
if (acctNum == defacctNum) {
cout << "Enter your pin: ";
cin >> acctPin;
while (acctPin != defacctPin) {
cout << "Wrong pin please enter it again: ";
cin >> acctPin;
}
if (acctPin == defacctPin) {
cout << "You have $" << defacctBal << " in you account." << endl;
int check2;
cout << "Would you like to deposit or withdraw? Press 1 to deposit, 2 to withdraw or any other key to exit." << endl;
cin >> check2;
if (check2 == 1) {
cout << "Enter the amount you want to deposit.: " << endl;
cin >> deposit;
cout << "You deposited $" << deposit << ".";
defacctBal += deposit;
cout << "Your account balance is now $" << defacctBal << "." << endl;
}
else if (check2 == 2) {
cout << "Enter amount you want to withdraw." << endl;
cin >> withdraw;
while (withdraw > defacctBal) {
cout << "You can't withdraw more than you have!" << endl;
cin >> withdraw;
}
if (withdraw < defacctBal) {
defacctBal -= withdraw;
cout << "You withdrew $" << withdraw << ", now you have $" << defacctBal << endl;
}
}
}
}
}
else if (check == 2) {
int acctNums;
cout << "Enter your name: ";
cin >> name;
cout << "Welcome to Obadan Bank, " << name << ", we would be generating an account number for you.";
acctNums = rand() % 999999 + 100000;
cout << "..l o a d i n g..." << endl;
cout << "You new account number is: " << acctNums << ". Please enter your new pin: " << endl;
cin >> acctPin;
cout << "Confirm pin again." << endl;
int pinConf;
cin >> pinConf;
while (acctPin != pinConf) {
cout << "Please make sure both pins match!" << endl;
cin >> pinConf;
}
if (pinConf == acctPin) {
cout << "Welcome to your new account, " << name << ". Would you like to start off with a deposit? Hit 1 to deposit or any other key to exit." << endl;
int conf;
cin >> conf;
if (conf == 1) {
cout << "Enter your deposit amount." << endl;
cin >> deposit;
cout << "Great! You deposited $" << deposit << "." << endl;
}
}
}
cin >> yo;
return 0;
}
Although as suggested by Paul, Questions about improving working code belong on codereview.stackexchange.com, but still here's a short architectural answer to your question
1)Create a BankAccount Class along with a BankCustomer class something like this:
class BankCustomer
{
//Member variables representing state of the object
BankAccount bankAcct;
std::string customerName;
.... //All other customer specific details in form of member variables
//Member functions for performing operations on this object
}
class BankAccount
{
//Member variables representing "state"
//Member functions to perform operations like:
"CreateAccount()"
"DepositToExistingAccount(int accountNumber)"
"WithdrawFromExistingAccount(int accountNumber)"
};
In your client application(say main.cpp), create BankCustomer objects in a do-while loop. Imagine that this is the bank manager performing this operation to service different BankCustomers.
int main()
{
std::string option;
cin>>option;
do
{
//Here ask the different choices like
1. New User Creation
2. Operations on Existing User:
a) Deposit
b) Withdraw
3. Exit
}while(option != "Exit")
}
Cheers,
Deepak

C++ Array Object Checking Values

I am supposed to write a program with two classes, Employee and Department. When the main() function runs, it asks the user to choose one of the six numbered options that are displayed and creates arrays for Employee and Department objects. I'm disregarding every other option except option 1, the Create Department Option, so the focus of this issue will be the Department class and the Department department[3] array.
There is a while loop in the main() function that continuously runs until the user decides to exit. If the user enters option 1, a Department array object is created, and then the user also enters the departmentID, departmentName, and departmentHeadName for that object. The while loop notifies the user if the array has three Employee objects. However, I am having difficulties because each departmentID needs to be unique. For example, I cannot enter 1 for the first array object's departmentID, and then enter 1 again for the second array object's departmentID. How do I check if the user's departmentID input already exists in a previous object?
#include <iostream>
#include <string>
using namespace std;
// Employee Class
class Employee
{
private:
string employeeID;
string employeeName;
string employeeDepartmentID;
double employeeSalary;
int employeeAge;
public:
void createEmployee()
{
cout << "Please Enter Employee Details:" << endl;
cout << "Employee ID : ";
cin >> employeeID;
cout << "Employee Name :";
cin >> employeeName;
cout << "Salary: $";
cin >> employeeSalary;
cout << "Age : ";
cin >> employeeAge;
cout << "Department ID : ";
cin >> employeeDepartmentID;
}
};
// Department Class
class Department
{
private:
string departmentID;
string departmentName;
string departmentHeadName;
public:
void createDepartment()
{
cout << "Please Enter Department Details: \n";
cout << "Department ID : ";
cin >> departmentID;
cout << "Department Name : ";
cin >> departmentName;
cout << "Head of Department : ";
cin >> departmentHeadName;
}
};
// Function prototype
void displayMenu();
// Client main function
int main()
{
Employee employee[5];
Department department[3];
int choice;
int departmentCount = 0;
int employeeCount = 0;
while (true)
{
displayMenu();
cin >> choice;
if (choice == 1 && departmentCount < 3)
{
department[departmentCount].createDepartment();
departmentCount = departmentCount + 1;
}
else if (choice == 1 && departmentCount >= 3)
{
cout << "\nThe array is full, you can not add any more Departments." << endl;
}
else if (choice == 2 && employeeCount < 5)
{
employee[employeeCount].createEmployee();
employeeCount = employeeCount + 1;
}
else if (choice == 2 && employeeCount >= 5)
{
cout << "The array is full, you can not add any more Employees." << endl;
}
else if (choice == 6)
{
cout << "Thank you, goodbye." << endl;
break;
}
}
return 0;
}
// Display menu function
void displayMenu()
{
cout << "1. Create Department" << endl;
cout << "2. Create Employee" << endl;
cout << "3. Write Out Data File" << endl;
cout << "4. Read In Data File" << endl;
cout << "5. Display Salary Report" << endl;
cout << "6. -- Quit -- " << endl;
cout << "Please make a selection : ";
}
try this one
#include <iostream>
#include <string>
using namespace std;
// Employee Class
class Employee
{
private:
string employeeID;
string employeeName;
string employeeDepartmentID;
double employeeSalary;
int employeeAge;
public:
void createEmployee()
{
cout << "Please Enter Employee Details:" << endl;
cout << "Employee ID : ";
cin >> employeeID;
cout << "Employee Name :";
cin >> employeeName;
cout << "Salary: $";
cin >> employeeSalary;
cout << "Age : ";
cin >> employeeAge;
cout << "Department ID : ";
cin >> employeeDepartmentID;
}
};
// Department Class
class Department
{
private:
string departmentID;
string departmentName;
string departmentHeadName;
public:
void createDepartment()
{
cout << "Please Enter Department Details: \n";
cout << "Department ID : ";
cin >> departmentID;
cout << "Department Name : ";
cin >> departmentName;
cout << "Head of Department : ";
cin >> departmentHeadName;
}
public:
string getDepartmentID(){
return departmentID;
}
};
// Function prototype
void displayMenu();
// Client main function
int main()
{
Employee employee[5];
Department department[3];
int choice;
int departmentCount = 0;
int employeeCount = 0;
while (true)
{
displayMenu();
cin >> choice;
if (choice == 1 && departmentCount < 3)
{
department[departmentCount].createDepartment();
for(int i=0;i<departmentCount;i++)
{
if(department[i].getDepartmentID()==department[departmentCount].getDepartmentID())
{
cout<<"already exists......................... \n";
}
}
departmentCount = departmentCount + 1;
}
else if (choice == 1 && departmentCount >= 3)
{
cout << "\nThe array is full, you can not add any more Departments." << endl;
}
else if (choice == 2 && employeeCount < 5)
{
employee[employeeCount].createEmployee();
employeeCount = employeeCount + 1;
}
else if (choice == 2 && employeeCount >= 5)
{
cout << "The array is full, you can not add any more Employees." << endl;
}
else if (choice == 6)
{
cout << "Thank you, goodbye." << endl;
break;
}
}
return 0;
}
// Display menu function
void displayMenu()
{
cout << "1. Create Department" << endl;
cout << "2. Create Employee" << endl;
cout << "3. Write Out Data File" << endl;
cout << "4. Read In Data File" << endl;
cout << "5. Display Salary Report" << endl;
cout << "6. -- Quit -- " << endl;
cout << "Please make a selection : ";
}
I used getDepartmentID function in Department Class to get department id from each department object
public:
string getDepartmentID(){
return departmentID;
}
there should be return type is string.because you have created departmentID as a string.
and I used For Loop in main function to compare relevant department id already exists or not
for(int i=0;i<departmentCount;i++)
{
if(department[i].getDepartmentID()==department[departmentCount].getDepartmentID())
{
cout<<"already exists......................... \n";
}
}

c++ programming function error

my full code is (couldn't make it smaller) :
/*password is admin*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;
//-------------------------------
fstream d_base;
char path[] = "library books.txt";
void output(){
//this function for displaying choices only
cout << "***********************************" << endl;
cout << "1. List all books in library" << endl;
cout << "2. List available books to borrow " << endl;
cout << "3. Borrow a Book from library" << endl;
cout << "4. Search For a Book" << endl;
cout << "5. Add New Books"<< endl;
cout << "6. Delete a Book" << endl;
cout << "7. EXIT The Library"<< endl;
cout << "***********************************" << endl;
}
//=====================================================================================================================================================
struct books{
//identfying books with all needed things
int id, status;
string title, p_name, p_address;
string aut_name, aut_nationality;
string date;
};
//=====================================================================================================================================================
//function for choice 1 showing the books (under constructions)
void choice1(){
ifstream show;
char all;
show.open(path, ios::in | ios::app);
while (!show.eof()){
show >> all;
if (all == '%'){
cout << "\n\n";
}
else if (all == '.'){
cout << "\n\n\n";
}
else
cout << all;
}
cout << endl;
show.close();
}
//=====================================================================================================================================================
void choice2(){
//function for choice 2 (list available books to borrow)
}
//=====================================================================================================================================================
void choice3(){
//function for choice 3( Borrow a Book )
}
//=====================================================================================================================================================
void choice4(){
char s;
ifstream search;
char idx;
cout << "what book you want to search for : ";
cin >> idx;
search.open(path, ios::in | ios::app);
while (!search.eof()){
search >> s;
if (s == idx)
cout << "book found" << endl;
break;
}
search.close();
}
//=====================================================================================================================================================
//for choice 5 to fill books (under constructions)
void choice5(books new_book[],books aut[], int books_number,int aut_number){
//function for adding books to the system
cout << "how many books you want to add ? ";
cin >> books_number;
//call the function to record the book
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < books_number; i++){
d_base << "[Book Id]: " << new_book[i].id << "%[title]: " << new_book[i].title;
d_base << "%[Publisher Name]: " << new_book[i].p_name << "% [puplisher Address]: " << new_book[i].p_address;
for (int j = 0; j < aut_number; j++){
d_base << "%[author info]" << "%[Authors Name]: " << aut[i].aut_name << "%[Nationality]: " << aut[i].aut_nationality;
}
d_base << "%[PublishedAt]: " << new_book[i].date << "%[status]:" << new_book[i].status << "." << endl;
}
d_base.close();
}
//=====================================================================================================================================================
void choice6(){
//function for searching for a book
}
//=====================================================================================================================================================
int main(){
string choice;
cout << "welcome to FCIS library\n\n";
do{
output();
cout << "what do you want to do ? ";
getline( cin , choice);
if (choice == "1"){
choice1();
}
//this one for list available books
else if (choice == "2"){
choice2();
}
//this one for borrow a book
else if (choice == "3"){
//not completed yet don't choose 3
}
else if (choice == "4"){
choice4();
}
//this one is for adding new books to the list
else if (choice == "5"){
int books_number, aut_number;
books new_book[10000], aut[10000];
string password;
do{
cout << "you must be an admin to add new books." << endl << "please enter passowrd (use small letters) : ";
cin >> password;
if (password == "b")
break;
else if (password == "admin"){
cout << "ACCESS GAINED WELCOME " << endl;
cout << "what books you want to add :" << endl;
for (int i = 0; i < books_number; i++){
cout << "id please : "; cin >> new_book[i].id;
cout << "title : "; cin.ignore(); getline(cin, new_book[i].title);
cout << "publisher name :"; getline(cin, new_book[i].p_name);
cout << "publisher address : "; getline(cin, new_book[i].p_address);
cout << "Publish date :"; getline(cin, new_book[i].date);
cout << "How many copies of " << new_book[i].title << " "; cin >> new_book[i].status;
cout << "How Many Authors for the Book ?"; cin >> aut_number;
for (int j = 1; j <= aut_number; j++){
cout << "author number " << j << " name : "; cin.ignore(); getline(cin, aut[i].aut_name);
cout << "Nationality : "; getline(cin, aut[i].aut_nationality);
choice5(new_book[i], aut[j], books_number, aut_number);
}
}
}
else{
cout << "Wrong password try again or press (b) to try another choice";
continue;
}
} while (password != "admin");
}
//this one for deleteing a book
else if (choice == "6"){
//not completed yet
}
else if (choice == "7"){
cout << "Thanks for Using FCIS LIBRARY" << endl;
break;
}
else
cout << "\nwrong choice please choose again\n\n";
} while (true);
}
the problem is when i call the choice5() function it gets me errors :
*-IntelliSense: no suitable conversion function from "books" to "books
*-IntelliSense: no suitable conversion function from "books" to "books
-error C2664: 'void choice5(books [],books [],int,int)' : cannot convert argument 1 from 'books' to 'books []
i don't know if it's parameters problem or what!!
the choice5(); function call is in the main in the if(choice==5) after submitting books
and i'm like level 1 at c++ so i'm doing my best to make it smaller
i don't know if it's parameters problem or what!!
The compiler tells you exactly what and where the problem is: your call to choice5. The first parameter is an array of books and you're passing in a single book.
choice5(new_book[i], aut[j], books_number, aut_number);
new_book is an array, new_book[i] is a particular book in the array. Same goes for aut.
The function choice5(books new_book[],books aut[], int books_number,int aut_number) must receive as first parameter an array of books or a pointer to a struct books. You will have the same problem with the second parameter "aut". To match with the functioon definiton your call shall have this format :
choice5(new_book, aut, books_number, aut_number)

array based database not working correctly

I have to write a program for an array based database that will allow the user to enter new data, update existing data, delete entries and view a list of the entries. The requirements are a structure called DATE, a structure called CustData that holds the user data, an array of type CustData with a size of 10 and requires an individual function for entering, updating, deleting and displaying the customer data. It also needs to use a while loop to initialize each index in the array with everything initialized to 0. I have a rough program written but the more I work on it the more I feel like I am doing it completely wrong. So far I have it working to the point that it lets me add multiple entries without overwriting previous ones, but I can't seem to be able to limit the number of entries I can input. I also have the displaying of entries correct. Any help that could be offered is greatly appreciated, below is my program so far, with some of the data input sections commented out to make testing it easier. My apologies for leaving this out, this is in C++, written with visual studio 2013.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct Date
{
int month,
day,
year;
};
struct cust
{
int ID;
string name;
string address;
string city;
string state;
string zip;
string phone;
double balance;
Date lastpayment;
};
const int SIZE = 10;
int menuchoice;
int num = 0;
int i;
void showmenu();
void funcentercustdata(cust[], int);
void funcupdatecustdata();
void funcdeletecustdata();
void funcdisplaycustdata(cust[], int);
cust custdb[SIZE];
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
showmenu();
int index;
for (index = 0; index < SIZE; index++)
{
custdb[index].ID = 0;
custdb[index].name = "";
custdb[index].address = "";
custdb[index].city = "";
custdb[index].state = "";
custdb[index].zip = "";
custdb[index].phone = "";
custdb[index].balance = 0.00;
custdb[index].lastpayment.month = 0;
custdb[index].lastpayment.day = 0;
custdb[index].lastpayment.year = 0;
}
return 0;
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
cout << "Please enter your choice: ";
cin >> menuchoice;
do
{
switch (menuchoice)
{
case 1:
funcentercustdata(custdb, SIZE);
showmenu();
break;
case 2:
funcupdatecustdata();
showmenu();
break;
case 3:
funcdeletecustdata();
showmenu();
break;
case 4:
funcdisplaycustdata(custdb, SIZE);
showmenu();
break;
case 5:
cout << "Thank you and have a nice day!\n";
break;
default:
cout << "Please enter a correct choice\n";
cin >> menuchoice;
break;
}
} while (menuchoice != 5);
}
void funcentercustdata(cust custinfo[], int size)
{
if (custinfo[i].ID != 0)
{
i++;
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
else if (custinfo[i].ID != 0 && custinfo[i].ID >= 4)
{
cout << "No further inputs allowed\n";
}
else
{
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
}
void funcupdatecustdata()
{
cout << "insert function 2\n\n";
}
void funcdeletecustdata()
{
cout << "insert function 3\n\n";
}
void funcdisplaycustdata(cust custinfo[], int size)
{
for (int i = 0; i < size; i++)
{
if (custinfo[i].ID == 0)
cout << " ";
else if (custinfo[i].ID != 0)
{
cout << "\n\nClient ID: " << custinfo[i].ID << endl;
cout << "Client name: " << custinfo[i].name << endl;
/* cout << "Client address: " << custinfo[i].name << endl;
cout << "Client city: " << custinfo[i].name << endl;
cout << "Client state: " << custinfo[i].name << endl;
cout << "Client zip: " << custinfo[i].name << endl;
cout << "Client phone: " << custinfo[i].name << endl;*/
cout << "Client balance: " << custinfo[i].balance << endl;
cout << "Client last deposit: " << custinfo[i].lastpayment.month << "/" <<
custinfo[i].lastpayment.day << "/" << custinfo[i].lastpayment.year << endl;
}
}
}
You've asked multiple questions concerning the issues in your program. So I will look at the first question:
I can't seem to be able to limit the number of entries I can input
First, your code has some fundamental flaws. One flaw is the repeated calling of showmenu() while you're in the showmenu() function. This is a recursive call, and is totally unnecessary. Imagine if your program or similar program that was structured this way had to be running 24 hours a day, and there were thousands of entries added. You will evenutally blow out the stack with all the recursive calls. So this has to be fixed.
Second, showmenu(), at least to me, should do what it says, and that is "show the menu". It should not be processing input. Do the processing of input in a separate function.
Here is a more modularized version of the program:
#include <iostream>
void processChoice(int theChoice);
void showmenu();
void addCustomer();
void deleteCustomer();
int getMenuChoice();
int customerCount = 0;
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
int choice = 0;
do
{
showmenu();
choice = getMenuChoice();
if (choice != 5)
processChoice(choice);
} while (choice != 5);
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
}
int getMenuChoice()
{
int theChoice;
cout << "Please enter your choice: ";
cin >> theChoice;
return theChoice;
}
void processChoice(int theChoice)
{
switch (theChoice)
{
case 1:
addCustomer();
break;
//...
case 3:
deleteCustomer();
break;
}
}
void addCustomer()
{
if ( customerCount < 10 )
{
// add customer
// put your code here to add the customer
//...
// increment the count
++customerCount;
}
}
void deleteCustomer()
{
if ( customerCount > 0 )
{
// delete customer
--customerCount;
}
}
This is the basic outline of keeping track of the number of customers. Code organization and modularity is the key. The count of the current number of entries is either incremented or decremented wihin the addCustomer and deleteCustomer functions. Also note the test that is done in add/deleteCustomer().
In the main() function, note the do-while loop and the way it is set up. The showMenu function shows itself, the getMenuChoice function gets the choice and returns the number that was chosen.
If the choice is not 5, process the request. If it is 5, then the while part of the do-while kicks you out of the processing, otherwise you start back at the top (showMenu, getMenuChoice, etc). This avoids the recursive calls that your original code was doing.