C++ if statement in function - c++

So I am trying to write a basic program that will keep track of a balance, and you can make a withdraw, make a deposit, and quit the program altogether. This is the code.
#include <iostream>
#include <string>
using namespace std;
double balance = 0, withdraw = 0, deposit = 0;
string choice;
class Bank
{
public:
void withdrawMoney()
{
if(balance - withdraw >= 0)
{
balance = balance - withdraw;
}
else
{
cout << "$5 penalty for attempting to withdraw more than you have.";
balance -= 5;
}
}
public:
void depositMoney()
{
balance = balance + deposit;
}
};
int main()
{
Bank bankObject;
cout << "Welcome to the Bank Program!" << endl;
while(true)
{
cout << "Would you like to make a withdrawal, a deposit, or quit the program: ";
cin >> choice;
if(choice.compare("withdrawal") == 0)
{
cout << "Please enter the amount to withdraw: ";
cin >> withdraw;
bankObject.withdrawMoney();
cout << "New balance is: $" << balance << endl;
}
else if(choice.compare("deposit") == 0)
{
cout << "Please enter the amount to deposit: ";
cin >> deposit;
bankObject.depositMoney();
cout << "New balance is: $" << balance << endl;
}
else if(choice.compare("quit") == 0)
{
break;
}
else
{
cout << "Invalid input." << endl;
}
cout << "Would you like to try again or quit: ";
cin >> choice;
if(choice.compare("quit") == 0)
{
break;
}
}
cout << "Thank you for using the Bank Program." << endl;
return 0;
}
I am new to C++, (I started today), but I have previous experience with Java. I am continually getting an error at the withdraw method, at the first if statement, saying that I have an invalid use of the member function. Any help would be appreciated. Also, not sure if it matters, but I am using the IDE Code::Blocks.
EDIT: First problem fixed, but now there is another, when I run the code, I can get through it once just fine, but when I try to go through a second time by typing try again, it gets stuck in a loop and answers the first question as "incorrect input". Help?

You use withdraw as both a global variable and a method name. Renaming one of them should fix this particular error.
Edit: When you type "try again", your program only reads "try" (because the default is to break up the input by whitespace), leaving "again" in the buffer for the next read from cin. You can verify that with a few debugging output statements.

Related

Using goto function one of my user inputs won't work (c++)

I am writing a program that lets the user make their own person (as an object) with a series of user inputs and multiple choice. I have a confirmation system at the end using the goto function but when i go back to making making the person if they don't like it the user input for the fist name won't work but the rest do (the first name user input works the first time round perfectly fine)
Here is the code and an explanation:
Setting things up,making the class with a basic constructor function added on.
#include <iostream>
using namespace std;
class Person{
public:
string FirstName;
string Surname;
string Gender;
int Age;
double Money;
Person(string aFirstName, string aSurname, string aGender, int aAge, double aMoney){
FirstName = aFirstName;
Surname = aSurname;
Gender = aGender;
Age = aAge;
Money = aMoney;
}
};
Making the variables that will be put in the person at the end and getting them with user inputs and multiple choice:
int main(){
Error2:
string bFirstName;
string bSurname;
string bGender;
int bAge;
int Choice1;
int YesNo;
cout << "What is your character's First Name?" <<endl;
getline(cin, bFirstName);
cout << "What is your character's Surname?" <<endl;
getline(cin, bSurname);
Error1:
cout << "What is your character's Gender?" <<endl;
cout << "Press 1 for Male" <<endl;
cout << "Press 2 for Female" <<endl;
cout << "Press 3 for Other" <<endl;
cin >> Choice1;
switch(Choice1){
case 1:
bGender = "Male";
break;
case 2:
bGender = "Female";
break;
case 3:
cout << "Type in Gender." <<endl;
cin >> bGender;
break;
default:
cout << "Enter a valid choice next time" <<endl;
goto Error1;
break;
}
cout << "What is your character's Age?" <<endl;
cin >> bAge;
The confirmation system using goto functions so they can scrap the one they made and make a new one:
Error3:
cout << "Are you sure you want your character to have these attributes?" <<endl;
cout << "1 for yes, 2 for no" <<endl;
cout << "FirstName: " << bFirstName <<endl;
cout << "Surname: " << bSurname <<endl;
cout << "Gender: " << bGender <<endl;
cout << "Age: " << bAge <<endl;
cin >> YesNo;
if(YesNo == 1){
goto Error4;
} else if(YesNo == 2){
goto Error2;
} else{
goto Error3;
}
Error4:
Person Custom1(bFirstName, bSurname, bGender, bAge, 100);
return 0;
}
but if in the confirmation system I say I want to make a new one the goto function will work but asking for the first name will not work and it will immediately go to asking for the surname
and at the end when it asks if i'm fine with the attributes first name will be empty.
I recommend using loops for error correction and functionality continuations:
bool continue_program = true;
while (continue_program)
{
//...
std::cout << "Continue program (Y/N)?";
char response;
std::cin >> response;
response = tolower(response);
if (response != 'y') continue_program = false;
}
You can also use do-while for error correction:
int value = 25;
do
{
std::cout << "Enter the number 5: ";
std::cin >> value;
} while (value != 5);
This should eliminate a lot of your gotos.
I have solved the problem-I have got rid of goto's but that wasn't the problem.
I made YesNo a string and then made Error correction a do while loop and at the end I had to ask-Using getline-for the input of YesNo twice in the code but it only asked once when running I still have no idea what the problem was but I have fixed it.

Why do I need to press Enter twice after getline()?

Everything is working fine in this program except when it reaches getline() after cout<<"From Date: ";. At this point no matter if I give input or simply hit enter without input, I have to hit enter twice to proceed further. I tried removing cin.ignore() but it causes more problem by jumping over the first getline(). Here is the snippet which is causing this problem-
int main() {
Date d1;
int choice;
cout << "\nEnter choice: ";
cin >> choice;
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
switch (choice) {
case 1:
d1.diffbw();
break;
default:
cout << "Wrong choice";
}
return 0;
}
void Date::diffbw() {
Date current, ref;
string choice;
cout << "\n Type 'man' to enter date manually else hit Enter to insert current date!";
do {
cout << "From Date:";
getline(cin, choice);
if (choice == "man")
current.getdate(); //getdate() assigns day, month and year in object current
else if (choice.empty())
current = sysDate(); //sysDate returns system date
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
do {
cout << "To Date:";
getline(cin, choice);
if (choice.empty())
ref = sysDate();
else if (choice == "man")
ref.getdate();
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
current.calcAge(ref); //calcAge() calculates difference between two given dates.
cout << "\n Difference: ";
cout << abs(current.day) << " day(s) " << abs(current.month) << " month(s) " << abs(current.year) << " year(s)";
}
P.S.- I am using g++ compiler on windows.
Edit: I posted the whole function here as many people are having difficulty in understanding the context here. I also corrected the 'cin.ignore()' syntax as suggested by #john. I am trying to calculate difference between two given dates.
The second 'do while' loop works without any bug although it is completely synonymous with the first one.
It might be because you are first trying to get a value by calling cin.getline() and afterwards the program is done but is waiting for confirmation and it gets the confirmation by you pressing enter.
Basically
Enter Value: 5 //Presses enter
Press any key to exit window.
Your statement
cout<<"\n\n From Date:";
is strange and probably wrong, since the std::cout stream is generally buffered.
You should use std::cout << "From date:" << std::endl; and read a good C++ programming book and check in this C++ reference that you are correctly using every function or feature from the C++ standard library.
If you compile with a recent GCC, I recommend enabling all warnings and debug info, so compiling with g++ -Wall -Wextra -g. Then use your debugger, e.g. GDB.
If your computer runs some Linux or POSIX system, you could be interested in using GNU readline: then the input line becomes user-editable. You might also want to code a graphical application with Qt.
Everything is working fine in this program
How did you check that? What debugger did you use? What test cases do you have? Did you try to type something with spaces, e.g. today's date as the user input? What did happen?
I slightly modified your program to avoid relying on the Date class, which you did not define:
#include <string>
#include <iostream>
#include <limits>
#include <math.h>
#include <stdio.h>
using namespace std;
void diffbw();
int main() {
int choice;
cout << "\nEnter choice: ";
cin >> choice;
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
switch (choice) {
case 1:
diffbw();
break;
default:
cout << "Wrong choice";
}
}
void diffbw() {
string choice;
cout << "\n Type 'man' to enter date manually else hit Enter to insert current date!";
do {
cout << "From Date:";
getline(cin, choice);
cout << "choice";
if (choice == "man") {
}
else if (choice.empty()) {
}
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
do {
cout << "To Date:";
getline(cin, choice);
if (choice.empty()) {
}
else if (choice == "man") {
}
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
cout << "\n Difference: ";
}
and I don't see the same phenomenon you describe. That is, I don't need to press Enter twice. Please consider making your problematic program more minimal, and at the same time complete.

Trying to make an bank management System but having errors

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.

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.

Loop in C++ not working again

So I've been troubleshooting this program and I've already asked questions about it before. I've taken other people's advice seriously and have applied it to my program, but it's still not working. This is the modified (albeit shortened) code:
#include <iostream>
#include <string>
double balance, withdraw, deposit;
std::string choice;
void withdrawmon()
{
balance -= withdraw;
}
void depositmon()
{
balance += deposit;
}
int main()
{
std::cout << "Welcome to the Bank Program." << std::endl;
std::cout << "Enter a starting balance: ";
std::cin >> balance;
std::cin.clear();
do
{
std::cout << "Withdraw, deposit, or quit: ";
std::getline (std::cin, choice);
if(choice == "withdraw")
{
std::cout << "Enter amount to withdraw: ";
std::cin >> withdraw;
withdrawmon();
std::cout << "Your current balance is $" << balance << std::endl;
}
else if(choice == "deposit")
{
std::cout << "Enter amount to deposit: ";
std::cin >> deposit;
depositmon();
std::cout << "Your current balance is $" << balance << std::endl;
}
}
while(choice != "quit");
std::cout << "Thanks for using the Bank Program. Your final balance was $" << balance << std::endl;
return 0;
}
There wouldn't be a problem, and the code runs, but the output is like this:
https://www.dropbox.com/s/aocn6asjr4ofcws/Broken%20Output.PNG
As you can see the "Withdraw, deposit, or quit:" line prints itself twice whenever the loop restarts. Anyone know why? Any help is appreciated. I'm a new programmer as far as C++ goes, so any help is appreciated.
cin.clear() clears the error flag and leaves the remaining contents of the line that follow the input balance in the buffer. You need can call cin.ignore() to handle this properly.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You're mixing stream extraction operators with getline. In your example, std::cin>>withdraw got the string "50" when the user entered "50\n". The next getline just gets the "\n", which is why you get the prompt twice ("\n" != "quit").
You can solve this a few ways: Either use getline for everything and get what you need out of each line, call getline after your cin>> to make the next read operation begin at the next line, or, as Captain Oblivious suggested, use cin.ignore.