Trying to make an bank management System but having errors - c++

The things that i would like to accomplish is the functions of methods of the applications but getting many errors from the code which i don't completely understand and try to solve but came up with nothing.
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
class bank
{
char name [100],add[100],y;
int balance, amount;
public:
void open_account();
void deposite_money();
void withdraw_money();
void display_account();
};
void bank:open_account()
{
cout << "Enter your full name: ";
cin.ignore();
cin.getline(name,100);
cout << "What type of account you want to open savings (s) or current (c)";
cin >> y;
cout << "Enter amount of deposite: ";
cin >> balance;
cout << "Your account is created ";
}
void bank:deposite_money()
{
int a ;
cout << "Enter how much money you want to deposit: ";
cin >> a;
balance += a;
cout << "Your total deposit amount\n ";
}
void bank:display_account()
{
cout << "Enter the name: "<<name<<endl;
cout << "Enter your address: "<<add<<endl;
cout << "Type of account that you open: "<<y<<endl;
cout << "Amount you deposite: "<<balance<<endl;
}
void bank:withdraw_money()
{
cout << "Withdraw: ";
cout << "Enter the amount of withdrawing";
cin >> amount;
balance = balance - amount;
cout << "Now your total amount left is" <<balance;
}
int main()
{
int ch,x,n;
bank obj;
do
{
cout <<"01")open account\n";
cout <<"02")deposite money\n";
cout <<"03")withdraw money\n";
cout <<"04")display account\n";
cout <<"05")Exit\n";
cout << "Please select from the options above";
cin>>ch;
switch(ch)
{
case 1:"01")open account\n";
obj.open_account();
break;
case 2:"02")deposite money\n";
obj.deposite_money();
break;
case 3:"03")withdraw money\n";
obj.withdraw_money();
break;
case 4:"04")display account\n";
obj.display_account();
break;
case 5:
if(ch == 5)
{
cout << "Exit";
}
default:
cout<< "This is not the proper exit please try again";
}
cout << "\ndo you want to select the next step then please press : y\n";
cout << " If you want to exit then press : N";
x=getch();
if(x == 'y' || x == 'Y');
cout<< "Exit";
}
while (x == 'y' || x == 'Y');
getch();
return 0;
}
The errors that i am getting are
error stray '\'
error missing terminating character
error found ':' in nested name specifier
expected ; before ')' token
These are the errors that usually appears on the logs and has repeated a few times in different lines please help me so that i can finish this application i have learned a lot from making it and is looking forward to build more before my school starts Any help and suggestions on what i should do next is appreciated and advices on what i should do next will greatly be welcome for me to learn from this experience
Im using c++ btw and am trying to build some projects any advice for next time? How can improve myself after this errors and what should i next practice on like a next project that you guys would suggest me

See here:
#include <stdio.h>
#include <iostream>
using namespace std;
class bank
{
char name [100],add[100],y;
int balance, amount;
public:
void open_account();
void deposite_money();
void withdraw_money();
void display_account();
};
void bank::open_account()//: missing
{
cout << "Enter your full name: ";
cin.ignore();
cin.getline(name,100);
cout << "What type of account you want to open savings (s) or current (c)";
cin >> y;
cout << "Enter amount of deposite: ";
cin >> balance;
cout << "Your account is created ";
}
void bank::deposite_money()//: missing
{
int a ;
cout << "Enter how much money you want to deposit: ";
cin >> a;
balance += a;
cout << "Your total deposit amount\n ";
}
void bank::display_account()//: missing
{
cout << "Enter the name: "<<name<<endl;
cout << "Enter your address: "<<add<<endl;
cout << "Type of account that you open: "<<y<<endl;
cout << "Amount you deposite: "<<balance<<endl;
}
void bank::withdraw_money()//: missing
{
cout << "Withdraw: ";
cout << "Enter the amount of withdrawing";
cin >> amount;
balance = balance - amount;
cout << "Now your total amount left is" <<balance;
}
int main()
{
int ch,x,n;
bank obj;
do
{
cout <<"01)open account\n";//Delete " after Number
cout <<"02)deposite money\n";
cout <<"03)withdraw money\n";
cout <<"04)display account\n";
cout <<"05)Exit\n";
cout << "Please select from the options above";
cin>>ch;
switch(ch)
{
case 1:"01)open account\n";//Delete " after Number
obj.open_account();
break;
case 2:"02)deposite money\n";
obj.deposite_money();
break;
case 3:"03)withdraw money\n";
obj.withdraw_money();
break;
case 4:"04)display account\n";
obj.display_account();
break;
case 5:
if(ch == 5)
{
cout << "Exit";
}
default:
cout<< "This is not the proper exit please try again";
}
cout << "\ndo you want to select the next step then please press : y\n";
cout << " If you want to exit then press : N";
cin >> x;
if(x == 'y' || x == 'Y');
cout<< "Exit";
}
while (x == 'y' || x == 'Y');
}
Also don't use using namespace in headers, and in overall learn a better style. This is 80s C with C++ mixed in. Use containers not built in arrays, use iostream and overall get a good C++ book.

Related

Undeclared identifier- C++

I am doing a project for school and keep running into this reoccurring problem, my code does not seem to run as I have "undeclared identifiers." I have tried renaming them or redefining them but the same errors keep going or more. I am using VS code at the moment and read about maybe it was VScode itself but I get the same errors regardless.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class bankAccount {
public:
int accountNum;
string accountName;
string accountType;
double accountBalance;
double accountInterest;
double getInterest;
double updateBalance;
bankAccount(){
accountNum = 0;
accountName = "";
accountType = "";
accountBalance = 0.0;
accountInterest = 0.0;
}
void deposit()
{
long amount;
cout << "\n Please enter the amount you would like to deposit: ";
cin >> amount;
accountBalance = accountBalance + amount;
}
void withdraw()
{
long amount;
cout << "Please enter the amount you would like to withdraw: ";
cin >> amount;
if (amount <= accountBalance)
{
accountBalance = accountBalance - amount;
}
else
{
cout << "You do not have sufficient funds" << endl;
}
}
void interest(){
double getInterest;
cout << "Please enter desired interest amount: ";
cin >> getInterest;
}
void update(){
double updateBalance;
updateBalance = accountBalance * getInterest;
accountBalance += updateBalance;
}
void print(){
string print;
cout << "Welcome Back " << accountName << "," << endl;
cout << "\n Account Number: " << accountNum << endl;
cout << "\n Account Type: " << accountType << endl;
cout << "\n Current Balance: " << accountBalance << endl;
cout << "\n Account Interest: " << accountInterest << endl;
}
void openAccount(){
cout << "Enter Account Number: ";
cin >> accountNum;
cout << "Enter Account Holders Name: ";
cin >> accountName;
cout << "Enter Account Type: ";
cin >> accountType;
cout << "Enter Initial Balance: ";
cin >> accountBalance;
cout << "Enter Interest Rate: ";
cin >> accountInterest;
}
};
int main() {
int choice;
do
{
cout << "Please select the following options ";
cout << "\n 1:View Account";
cout << "\n 2: Open Account";
cout << "\n 3: Deposit" ;
cout << "\n 4: Withdraw ";
cout << "\n 5: Update account";
cin >> choice;
switch (choice)
{
case '1':
print ();
break;
case '2':
openAccount();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
updateBalance();
break;
}
} while (case !=5);
}
suggested creating an instance of class bankAccount somewhere before switch statement and call the functions like, instance_of_bankAccount.functionName();
At end of loop instead of (case !=5) it should be (choice != 5)
The problem with your code is that you do not have any instance of the class bankAccount, which means you try to call the function which actually does not exist. To fix it, you should create an object of the bankAccount type before the loop in which you can select the operation you want to perform:
int main() {
int choice;
bankAccount bankAcc; // this creates the object we need
do ...
And then for every case you wanted to call the function f(), add prefix bankAcc., so it becomes bankAcc.f(). In your code, it would be:
switch (choice) {
case '1':
bankAcc.print();
break;
case '2':
bankAcc.openAccount();
break;
case '3':
bankAcc.deposit();
break;
case '4':
bankAcc.withdraw();
break;
case '5':
bankAcc.updateBalance();
break;
}
Thanks to it, all functions called will know that they belong to bankAcc and they will change properties only of this particular object.
There is also another mistake in your code: did you really mean to use chars in your switch? At the moment cin >> choice reads an int, saves it in choice and then in switch it gets compared with all values corresponding to cases. The problem is that 1 is very different from '1' (which is casted to the value 49), so inputted int will never satisfy conditions from the menu you print.
Also, while (case !=5) should be changed to while (choice != 5).

Variable always resets to default in Functions

I am building an ATM sort of program where you can deposit and withdraw balance with the use of functions. I noticed at first that after i deposit first time, it works fine but after the second time using deposit it doesn't add it to the current balance but the balance before it.
For example:
(1st Attempt)
*Balance = 1000
*I deposit 500
*Balance is now = 1500
(2nd Attempt)
*I deposit 700
*Balance is now 1700
Instead of making it to 2200, it resets back to 1000 before went for my second attempt resulting in a result of 1700.
Can anyone please explain what went wrong in the code? I am willing to not only get the correct code but to also learn how it was done.
This is for my training in c++.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int deposit(int x, int y)
{
int newbal = x + y;
return newbal;
}
int withdraw(int x, int y)
{
int newbal = x - y;
return newbal;
}
int main()
{
int menu;
int selection;
double x = 1000, y;
int trans;
char user[20], pass[20], pktc[3];
string newuser, newpass;
do{
system ("CLS");
cout << "Welcome To Bank" << endl;
cout << "[1] Register" << endl;
cout << "[2] Login" << endl;
cout << "[3] Exit" << endl;
cout << "\n\nEnter command: " <<endl;
cin >> menu;
switch(menu)
{
//----------------------------------------------------------------CASE 1------------------------------------------------------------------------------//
//----------------------------------------------------------------REGISTER----------------------------------------------------------------------------//
case 1:
system ("CLS");
cout << "<-------REGISTER------->\n\n";
cout << "Enter Name: ";
cin >> user;
newuser = user;
cout << "Enter Password: ";
cin >> pass;
newpass = pass;
cout <<"REGISTERED SUCCESSFULLY!" << endl;
cout <<"\n\nPress Any key to contniue" << endl;
cin >> pktc;
system ("CLS");
break;
//------------------------------------------------------------END OF REGISTER--------------------------------------------------------------------------//
//----------------------------------------------------------------CASE 2------------------------------------------------------------------------------//
//-----------------------------------------------------------------LOGIN------------------------------------------------------------------------------//
case 2:
system ("CLS");
cout << "<-------LOGIN------->\n\n";
cout << "Enter Username: ";
cin >> newuser;
cout << "Enter Password: ";
cin >> newpass;
if(newuser != user || newpass != pass)
{
//-------------------------------------------------------------FAILED LOGIN----------------------------------------------------------------------------//
cout << "\nInvalid account" << endl;
cout <<"\n\nPress Any key to contniue" << endl;
cin >> pktc;
system ("CLS");
}
else if (newuser == user || newpass == pass)
{
//----------------------------------------------------------------CASE 2.1------------------------------------------------------------------------------//
//------------------------------------------------------------SUCCESFULL LOGIN--------------------------------------------------------------------------//
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
do{
cout<<"\n\nChoose Transaction[1-3]:";
cin>>trans;
switch(trans)
{
//----------------------------------------------------------------ATM CASE 1------------------------------------------------------------------------------//
//--------------------------------------------------------------CHECK BALANCE--------------------------------------------------------------------------//
case 1:
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nYour total balance is: "<< deposit(x, y) ;
break;
//----------------------------------------------------------------ATM CASE 2------------------------------------------------------------------------------//
//--------------------------------------------------------------BEFORE DEPOSIT--------------------------------------------------------------------------//
case 2:
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nEnter the amount:" ;
cin>>y;
//--------------------------------------------------------------AFTER DEPOSIT--------------------------------------------------------------------------//
system ("CLS");
cout << "\n\n<-------------------------------WELCOME------------------------------->\n\n" << endl;
cout<<"\nWelcome To Banco De Nelio";
cout<<"\nUSERNAME: "<< user << endl;
cout<<"\n\n TIP ATM MACHINE";
cout<<"\n 1. Balance";
cout<<"\n 2. Deposit";
cout<<"\n 3. Withdraw";
cout<<"\n 4. Exit";
cout<<"\n\nYour total balance now is: " << deposit(x, y) <<endl;
break;
//----------------------------------------------------------------ATM CASE 3------------------------------------------------------------------------------//
//--------------------------------------------------------------WITHDRAW BALANCE--------------------------------------------------------------------------//
case 3:
cout<<"\nEnter the amount:" ;
cin>>y;
if ( y > x)
{
cout<<"\nYou cannot withdraw " << y;
cout<<" because the amount is higher than your balance" << endl;
break;
}
else
x = x - y;
cout<<"\nYour Total Balance is now " << withdraw(x, y) << endl;
break;
//----------------------------------------------------------------ATM CASE 4------------------------------------------------------------------------------//
//-------------------------------------------------------------------BACK--------------------------------------------------------------------------------//
case 4:
cout<<"\n\nThank You!" << endl;
break;
default:
cout<<"\nYou did not enter any valid number" << endl;
break;
}
}while (trans<=3);
}
break;
//----------------------------------------------------------------CASE 3------------------------------------------------------------------------------//
//-----------------------------------------------------------------EXIT-------------------------------------------------------------------------------//
case 3:
system ("CLS");
cout << "Thank you for using me!\n";
return 0;
//-------------------------------------------------------------END OF EXIT----------------------------------------------------------------------------//
}
}while (menu<=3);
}
i am not sure if the problem here is the function or a conflict in switch statement.
Thanks In Advance
EDIT Please register first :)
Its really hard to spot the important pieces, but basically your problem can be boiled down to something like
int add(int x,int y) { return a+b; }
int sub(int x,int y) { return a-b; }
int main() {
int initial = 0;
// add 10 then subtract 5
std::cout << add(initial,10) << '\n'; // prints 10
std::cout << sub(initial,5) << '\n'; // prints -5
}
When what you actually want is something like
int main() {
int initial = 0;
// add 10 then subtract 5 and update initial
initial = add(initial,10);
std::cout << initial << '\n';
initial = sub(initial,5);
std::cout << initial << '\n';
}
Your methods correctly calculates the new amount, but when you call those methods you ignore the return value when instead you want to update some variable.
Some other suggestions (in random order):
use meaningful names. x and y do not convey any meaning, compare int deposit(int current_balance, int amount) to int deposit(int x,int y)
use functions to split your code into smaller pieces (eg it would be a good idea to seperate input, output and logic). Whenever you find yourself writing a comment describing what a block of code is doing, this block of code is a good candidate for a function that gets a proper name instead of a comment
dont use std::endl when you want to end a line (std::endl ends the line and flushes the stream, which is most of the time not what you want), use \n instead
dont use using namespace std;. It wont do much harm in your current code, but read here why you never should do it in a header, and better dont get used to bad habits from the start.

C++ Banking application not holding more than one account

Hello I've been working on a C++ banking application that should be able to hold more than one account with all the related field's. I have come across a few issues:
When displaying account info in Display or ShowInfo functions, the first letter of the first name and the middle initial wont show up.
When creating an account only the most recent account is able to be searched for and displayed in display data. I know that an array is needed for this to be possible, I'm just not sure if implemented this correctly.
Thanks for the help. Any input is appreciated!
#include <stdlib.h>
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
class BankAccount{
double Balance = 0.0;
char ans;
public:struct Name{
char Last_Name[50];
char First_Name[50];
char Middle_Initial[5];
}Name;
public:struct Account{
char Type[1];
int Account_Number;
}Account;
public:
void CreateAccount();
void Withdraw();
void Deposit();
void Display();
void ShowInfo();
int Menu();
};
void BankAccount::CreateAccount(){
do
{
cout << "\nEnter account number: ";
cin >> Account.Account_Number;
cout << "\nEnter the last name for the account: ";
cin.ignore();
cin.getline(Name.Last_Name, 50);
cout << "\nEnter the first name for the account: ";
cin.ignore();
cin.getline(Name.First_Name, 50);
cout << "\nEnter the Middle initial for the account: ";
cin.ignore();
cin.getline(Name.Middle_Initial, 5);
cout << "\nEnter the type of account (C/S) : ";
cin >> Account.Type;
cout << "\nEnter the initial balance of the account: ";
cin >> Balance;
cout << "\n\nAccount Created.";
cout << "\n\nCreate new account? (Y/N) : ";
cin >> ans;
while (ans != 'Y' && ans != 'N'){
cout << "Invalid input. Create new account? (Y/N) : ";
cin >> ans;
}
cout << endl;
} while (ans != 'N');
};
void BankAccount::Withdraw(){
int actNum;
double amount;
cout << "Enter the account number for the account that you wish to withdraw funds: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Enter the amount you would like to withdraw: ";
cin >> amount;
Balance = Balance - amount;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::Deposit(){
int actNum;
double amount;
cout << "Enter the account number for the account that you wish to deposit funds: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Enter the amount you would like to deposit: ";
cin >> amount;
Balance = Balance + amount;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::Display(){
int actNum;
cout << "Enter the account number for the account that you wish to display account information for: ";
cin >> actNum;
if (actNum == Account.Account_Number){
cout << "Account details for " << Name.First_Name << " " << Name.Middle_Initial << " " << Name.Last_Name << "'s account: " << endl;
cout << "Account Number: " << Account.Account_Number << endl;
cout << "Account Type (Checking / Savings): " << Account.Type << endl;
cout << "Account Balance: $" << Balance << endl;
}
else if (actNum != Account.Account_Number){
cout << "No account found under that number! Try again!";
}
}
void BankAccount::ShowInfo(){
cout << "Account details for " << Name.First_Name << " " << Name.Middle_Initial << " " << Name.Last_Name << "'s account: " << endl;
cout << "Account Number: " << Account.Account_Number << endl;
cout << "Account Type (Checking / Savings): " << Account.Type << endl;
cout << "Account Balance: $" << Balance << endl;
}
int main(int argc, char *argv){
BankAccount ob;
char ch;
cout << "Welcome to Console Banking Application V 1.0!";
cout << "\nSelect an item from the list below by entering the corresponding letter.";
do{
cout << "\n\n A. Create Account \n B. Withdraw \n C. Deposit \n D. Show Account Details \n\n Q. Exit Application\n\n";
ch = ob.Menu();
switch (ch){
case 'A':
case 'a': ob.CreateAccount();
ob.ShowInfo();
break;
case 'B':
case 'b': ob.Withdraw();
break;
case 'C':
case 'c': ob.Deposit();
break;
case 'D':
case 'd': ob.Display();
break;
case 'Q':
case 'q': ob.ShowInfo();
exit(1);
break;
}
} while (1);
}
int BankAccount::Menu(){
char ch;
cout << "Select an option: ";
cin >> ch;
return ch;
}
The simple answer is: You only have one bank account.
If you look at your main function, you create one, and only one BankAccount. As you would probably guess, one BankAccount cannot be used to represent multiple BankAccounts(SoAs aside).
Therefore, you need an array of BankAccounts. It goes something like this:
BankAccount obs[10];
Now you have 10 BankAccounts, no more. So every time you want to create a new BankAccount, just make sure that you create it on a BankAccount in the array that is not currently in use.
obs[0].CreateAccount();
obs[0].ShowInfo();
obs[0].Deposit();
//Make a new account
obs[1].CreateAccount();
...
To go even further, let's consider the fact that you have 10 BankAccounts, and only 10. This is not very extensive now is it? What's a bank with only 10 accounts available? Probably out of business in due time.
The naive solution would be to just add more. 50, 100, even 1000. But do you really want to go back and update that number every single time? That's way too tedious.
Fortunately, there's a convenient container we can use:
#include <vector>
...
std::vector<BankAccount> obs;
...
This is basically an array that expands itself automatically when required. I will not go into detail on how to use vectors because I am sure that you can easily learn to do so yourself. I will, however, leave you with this link so you know where you can start.

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.

Student Management System C++

I have this program in C++ for Student Management System , Everything is working fine , except one place where i try to delete a student based on his roll number .
What it should do : After asking the roll number search the record and delete it
What is it doing : It deletes all the other records which do not match that roll number
Here is my code :
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
FILE *fp, *ft;
char another, choice;
struct student {
char first_name[50], last_name[50];
int roll_num; //new code added
char course[100];
int section;
};
struct student e;
char xfirst_name[50], xlast_name[50];
int xroll_num ; // new code added
long int recsize;
fp=fopen("users.txt","rb+");
if (fp == NULL) {
fp = fopen("users.txt","wb+");
if (fp==NULL)
{
puts("Cannot open file");
return 0;
}
}
recsize = sizeof(e);
while(1) {
system("cls");
cout << "\t\t====== STUDENT INFORMATION SYSTEM ======";
cout <<"\n\n ";
cout << "\n\n";
cout<<" \n\t\t\t======================";
cout << "\n \t\t\t 1. Add Records";
cout << "\n \t\t\t 2. List Records";
cout << "\n \t\t\t 3. Modify Records";
cout << "\n \t\t\t 4. Delete Records";
cout << "\n \t\t\t 5. Exit Program";
cout<<" \n\t\t\t======================";
cout << "\n\n";
cout << "\t\t\t Select Your Choice ::";
fflush(stdin);
choice = _getche();
switch(choice)
{
case '1' :
fseek(fp,0,SEEK_END);
another ='Y';
while(another == 'Y' || another == 'y')
{
system("cls");
cout << "Enter the First Name : ";
cin >> e.first_name;
cout << "Enter the Last Name : ";
cin >> e.last_name;
cout << "Enter the Course : ";
cin >> e.course;
cout << "Enter the Section : ";
cin >> e.section;
cout << "Enter the roll number :";
cin >> e.roll_num;
fwrite(&e,recsize,1,fp);
cout << "\n Add Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '2':
system("cls");
rewind(fp);
cout << "=== View the Records in the Database ===";
cout << "\n";
while (fread(&e,recsize,1,fp) == 1){
cout << "\n";
cout <<"\nName :: " <<e.first_name <<" "<<e.last_name;
//cout << "\n";
cout <<"\nRoll Number :: " << e.roll_num ;
cout <<"\nCourse :: " <<e.course ;
cout <<"\nSection :: "<<e.section;
}
cout << "\n\n";
system("pause");
break;
case '3' :
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student : ";
cout << "\n Enter the Roll number of the student : ";
cin >> xroll_num;
rewind(fp);
while (fread(&e,recsize,1,fp) == 1)
{
//if (strcmp(e.last_name,xlast_name) == 0)
if(e.roll_num == xroll_num )
{
cout << "Enter the new Firt Name : ";
cin >> e.first_name;
cout << "Enter the new Last Name : ";
cin >> e.last_name;
cout << "Enter the new Roll Number : ";
cin >> e.roll_num;
cout << "Enter the new Course : ";
cin >> e.course;
cout << "Enter the new Section : ";
cin >> e.section;
fseek(fp, - recsize, SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
else
cout<<"record not found";
}
cout << "\n Modify Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '4':
system("cls");
another = 'Y';
while (another == 'Y'|| another == 'y')
{
// cout << "\n Enter the last name of the student to delete : ";
cout <<"\n Enter the roll number of the student to delete : ";
cin >> xroll_num;
ft = fopen("temp.dat", "wb");
rewind(fp);
while (fread (&e, recsize,1,fp) == 1)
// if (strcmp(e.last_name,xlast_name) != 0)
if(e.roll_num == xroll_num )
{
fwrite(&e,recsize,1,ft);
}
fclose(fp);
fclose(ft);
remove("users.txt");
rename("temp.dat","users.txt");
fp=fopen("users.txt","rb+");
cout << "\n Delete Another Record (Y/N) ";
fflush(stdin);
another = getchar();
}
break;
case '5':
fclose(fp);
cout << "\n\n";
cout << "\t\t THANK YOU FOR USING THIS SOFTWARE";
cout << "\n\n";
exit(0);
}
}
system("pause");
return 0;
}
It deletes all the other records which do not match that roll number
Well you're only writing the records that match the roll number to the temp file, and then using that file to overwrite the users.txt file
if (e.roll_num == xroll_num) {
fwrite(&e, recsize, 1, ft);
}
I suppose what you really wanted to do is
if (e.roll_num != xroll_num) {
fwrite(&e, recsize, 1, ft);
}
You should probably read a good C++ i/o tutorial, as your code is mostly C. Consider writing your student struct as simple text instead of writing it wholesale to the file.