I want to run another function after an if statement. The problem is the function I want to go to (main() ) is declared after it. Is there a possible work around?
1 2 3 4 5 6 7 8
cout << "Would you like to complete another transaction? (y/n)" << endl;
cin >> choice2;
if (choice2=="y")
// THIS iS WHERE I WANT TO START MAIN()
if (choice2=="n")
return(0);
#include <iostream>
#include <string>
usingnamespace std;
double b;
string choice2;
int withdraw() {
double w=0;
cout << "How much would you like to withdraw?" << endl;
cout << "Withdraw: ";
cin >> w;
if (w>b) {
cout << "Insuffecient funds" << endl;
cout << "Try again" << endl;
cin >> w;
}
b=b-w;
cout << "Your balance is now $" << b << endl;
cout << endl;
cout << "Would you like to complete another transaction? (y/n)" << endl;
cin >> choice2;
if (choice2=="y")
// THIS iS WHERE I WANT TO START MAIN()
if (choice2=="n")
return(0);
}
int deposit() {
double d=0;
cout << "How much would you like to deposit?" << endl;
cout << "Deposit: ";
cin >> d;
if (d<0) {
cout << "Can't be negatives!" << endl;
cout << "Try again!" << endl;
d=d*-1+d;
cout << "Deposit: ";
cin >> d;
}
b=d+b;
cout << "Your balance is now $" << b << endl;
cout << endl;
cout << "Would you like to complete another transaction? (y/n)" << endl;
cin >> choice2;
if (choice2=="y")
// THIS IS WHERE I WANT TO START MAIN
if (choice2=="n")
return(0);
}
int main() {
string choice;
cout << "Hello and welcome to CS Bank!" << endl;
cout << "What is your balance?" << endl;
cin >> b;
if (b<0) {
cout << "Can't be a negative!" << endl;
cout << "Try again!" << endl;
cin >> b;
}
if (!( b > 0 || b < 0)) {
cout << "Not a valid number" << endl;
cout << "Balance: " << endl;
cin >> b;
}
cout << "Would you like to withdraw, deposit or view balance?" << endl;
cin >> choice;
if (choice== "withdraw")
withdraw();
if (choice=="deposit")
deposit();
if (choice=="balance")
cout << "Balance: $" << b << endl;
if (choice!="withdraw" && choice!="deposit" && choice != "balance") {
cout << "Incorrect input!" << endl;
}
}
First of all you should always avoid using global variables. Second you can pass the balance by reference to the functions in order that they sustain the changes. Next you can do what you want in the main with a character and a do-while loop. The code will be something like this.