atm code issue with displaying pre existing balances - c

I have an assignment where i'm supposed to simulate an ATM machine. The issue i'm running into is that my code only shows the last variable embedded within the variable "currBal" and not all 3. I have an idea that i might possibly need to use a pointer to differentiate which account to pull from but i'm lost from then on.
IE: double currBal = (checking,savings,credit);
when running the code the pre existing balance shows only the credit amount of -750 for checking savings and credit (should only show for credit, while checkings and savings should show their respective #defined amounts before deposits and withdrawals.) The only things i'm missing now is showing all 3 pre existing balances,and making sure the withdrawal and deposits work for their respective accounts.
Thank you for the help!
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define CREDITLIMIT -2000
#define credit -750.00
#define savings 3750.00
#define checking 897.23
//* Displays the list of user’s options available
//** Displays the user’s selections and sets the value of the choice
void entryMenu(int *choice);
//Prompts the user for the amount of their deposit and updates the selected account
void MakeDeposit(double *currBal);
//Asks the user if they want another transaction
void DoMore(char * doAgain);
//Displays the types of account they would like to access and sets the
//value of the chosen account type
void ChoiceMenu(char *acctType);
//Prompts the user for the amount of the withdrawal, determines if there are
//sufficient funds and updates the selected account if funds are dispensed
void MoneyToSpend(double *currBal);
//Displays the user’s current account balance for the selected account
void DisplayBalance(double currBal);
int main()
{
double currBal = (checking, credit, savings);
int choice;
char doAgain = 0;
char acctType;
while (1) {
printf("Welcome to MYBANK\n");
printf("Please choose from the following menu\n");
do {
entryMenu(&choice);
switch (choice) {
case 1://Deposit
ChoiceMenu(&acctType);
MakeDeposit(&currBal);
DoMore(&doAgain);
break;
case 2://withdrawal
ChoiceMenu(&acctType);
MoneyToSpend(&currBal);
DoMore(&doAgain);
break;
case 3://account balance
ChoiceMenu(&acctType);
DisplayBalance(currBal);
DoMore(&doAgain);
break;
//choices that are not 1,2,3
default:
printf("invalid Choice");
DoMore(&doAgain);
}
} while (doAgain == 'Y' || doAgain == 'y');
return 1;
}
return 0;
}
//*Displays the list of user’s options available
//**Displays the user’s selections and sets the value of the choice
void entryMenu(int *choice)
{
printf("1 - DEPOSIT \n");
printf("2 - WITHDRAWAL \n");
printf("3 - CHECK ACCOUNT BALANCE \n");
printf("Important: ");
printf("To transfer money first select \n(2) for WITHDRAWAL, then \n(1) for DEPOSIT\n");
scanf(" %d", choice);
}
//Prompts the user for the amount of their deposit and updates the selected account
void MakeDeposit(double *currBal)
{
float deposit;
printf("Please enter the amount of the deposit: ");
scanf("%f", &deposit);
*currBal += deposit;
printf("Thank you, please take your cash and receipt\n");
}
//Asks the user if they want another transaction
void DoMore(char * doAgain)
{
int choice;
printf("Would you like to make another transaction?\n");
printf("(Y)es / (N)o ? \n");
scanf(" %c", doAgain);
}
//Displays the types of account they would like to access and sets the
//value of the chosen account type
void ChoiceMenu(char *acctType)
{
printf("Please select account: \n");
printf("Choose C for Checking\n");
printf("Choose S for Savings\n");
printf("Choose R for Credit\n");
scanf(" %c", acctType);
}
//Prompts the user for the amount of the withdrawal, determines if there are
//sufficient funds and updates the selected account if funds are dispensed
void MoneyToSpend(double *currBal, char acctType)
{
float withdrawal;
{
printf("Please enter the amount of the withdrawal: ");
scanf("%f", &withdrawal);
{
if (*currBal < withdrawal)
{
printf("You do not have enough\n\n");
}
else if (*currBal > withdrawal)
{
*currBal -= withdrawal;
}
}
}
}
//Displays the user’s current account balance for the selected account
void DisplayBalance(double currBal)
{
printf("\nYou have %.1f in your account\n", currBal);
}

Related

I want to create a menu that shows 1. Client details, 2.Property details and 3. Exit

I want to create a menu that shows:
Client details
Property details
Exit
#include <stdio.h>
#include <conio.h>
void main() {
char L,F,H;
float CID,Aoc,Pte,Cost_per_sqft;
int dicnt,age,ch;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%f", &Aoc);
if (age >=60) {
printf("The client is eligible for a discount\n");
} else if (age<60) {
printf("The client is not eligible for a discount\n");
} {
printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("Client ID %f", CID);
printf("Age of client %f", Aoc);
}
}
It's not letting me enter the option to open a menu, also the age else is doesn't work because age => 60 is also showing not eligible for discount. The switch case doesn't work either.
Problem 1 is that you have defined two variables, float Aoc and int age, then attempt to use them interchangeably. Also, the first time age is referenced ( here: if (age >=60) ) it is uninitialized, which contributes to the problems you have described.
Addressing the following will fix the if-else statement for age, and will allow the menu to appear...
Since age is typically a non-float value, i.e. 45 or 50, but never expressed as 45.5.
Suggest replacing, Aoc everywhere it exists with age, (modifying the format specifiers accordingly), and finally, initialize age before use.
Problem 2 is here:
...
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
You are prompting user to input a char value, then attempt to read it in into a float variable Pte. Suggest if desiring to read in as a char, use a " %c" format specifier, and change float Pte to char Pte.
(Note space in format specifier, it is there for this reason.)
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);//note space in front of %c to consume newline
Working code adapted from your original:
void main()
{
char L,F,H;
float CID,Aoc;/*Pte*/
float Cost_per_sqft;
int dicnt,age,ch;
char Pte;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%d", &age);
if (age >=60)
{
printf("The client is eligible for a discount\n");
}
else if (age<60)
{
printf("The client is not eligible for a discount\n");
}
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Client ID %f\n", CID);
printf("Age of client %d", age);
break;
case 2:
;//add content
break;
case 3:
;//add content
break;
}
}

Passing the value from this function

#define _CRT_SECURE_NO_WARNINGS
/*
Purpose: This program allows the user to bet on horses
in a race to earn money on said wagers. I'm trying to run the configureBalance function and then add money to the balance. I'm getting an exception read access violation
*/
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH myFlush()
//Prototyping
void getChoice(char *userChoice); // main menu choice
void displayMenu(); // visual menu
void myFlush(); // flush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit); // this function is for editing account credentials
void currentBalance(int *balance); // displays the account balance
void coolRaceVisual(); // cool looking visual
//Structs
main() {
int balance = 0, wallet = 0, withdraw = 0, deposit = 0;
char choice = ' ';
do {
getChoice(&choice);
switch (choice) {
case 'A':
configureBalance(balance, wallet, withdraw, deposit);
PAUSE;
break;
case 'B':
coolRaceVisual();
PAUSE;
break;
case 'Q':
CLS;
printf("[][][][][][][][][][][]\n");
printf("[] Goodbye ! []\n");
printf("[][][][][][][][][][][]\n");
break;
default:
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
printf("[] Invalid Selection! Please try again []\n");// This
prompt shows up when the user
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
inputs something incorrectly
PAUSE;
CLS;
break;
return;
}
} while (choice != 'Q');
PAUSE;
}//end main
void getChoice(char *userChoice) {
displayMenu();
scanf("%c", userChoice); FLUSH;
*userChoice = toupper(*userChoice);
}//end getChoice
void displayMenu() {
CLS;
printf(" Horse Derby Ticket Office \n");
printf(" \n");
printf(" A) Configure Balances. \n");
printf(" \n");
printf(" B) Watch the Race. \n");
printf(" \n");
printf(" C) View Race Records. \n");
printf(" \n");
printf(" D) Save and Quit. \n");
printf(" \n");
printf(" Q) Quit. \n");
printf(" \n");
}// end displayMenu
void myFlush() {
while (getchar() != '\n');
}//end myFlush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit) {
CLS;
char configureMenuChoice = ' ';
printf("What service would you like? (Not FDIC Insured)\n\n");
printf("A) Add funds to your account balance.\n");
printf("B) Withdraw funds to your wallet.\n");
printf("C) Check Account Balance.\n");
printf("\n\n");
scanf("%c", &configureMenuChoice);
configureMenuChoice = toupper(configureMenuChoice);
Uppercases the choice configuring balances
if (configureMenuChoice == 'A') {
CLS;
printf("How much would you like to add to your account balance? \n");
This adds directly to the balance
scanf("%i", &deposit);
*balance = *balance + *deposit;
}
if (configureMenuChoice == 'C') {
CLS;
currentBalance(*balance); // displays current balance, made a functino so it can be used at will
}
}//end conFigureBalance
void currentBalance(int *balance) {
printf("Your current balance is: %i\n", &balance);
}//end checkBalance
Change this:
scanf("%i", &deposit);
to this:
scanf("%i", deposit);
since deposit is of type int* in that context (the body of the function configureBalance).
It's the same logic as followed here: scanf("%c", userChoice);, so I wonder how you missed it.

Setting A Balance For My C ATM

Hey guys I am constructing an ATM Program, and I have everything ok
I have the menu it pulls up you can select an option and it runs the function HOWEVER, I cannot for the life of me
set a balance and
get it to stay until its changed
and I need it to save once it has changed in one of the two options (deposit, withdrawl) since this is a post test loop it will keep going until exit is selected and every time I need this to update the balance.
Here is my C Code for it, if anyone could help that would be amazing.
#include <stdio.h>
#include <stdlib.h>
// Function Declarations
int getChoice ();
double withdraw (int Choice, int Balance);
double deposit (int Choice, int Balance);
int VBalance (int Choice, int Balance);
double process (int Choice, int Balance);
int main (void)
{
// Local Declarations
int Choice;
int Balance;
// Statements
do
{
Balance = 2500.00;
Choice = getChoice ();
process (Choice, Balance);
}
while (Choice != 0);
return 0;
} // Main
/*============================process=*/
double process (int Choice, int Balance)
{
// Declarations
// Statements
switch(Choice)
{
case 1: withdraw (Choice, Balance);
break;
case 2: deposit (Choice, Balance);
break;
case 3: VBalance (Choice, Balance);
break;
case 0: exit;
break;
deafult: printf("Sorry Option Not Offered");
} // switch
return 0;
}
/*============================getChoice=*/
int getChoice (void)
{
// Local Declarations
char Choice;
// Statements
printf("\n\n**********************************");
printf("\n MENU ");
printf("\n\t1.Withdrawl Money ");
printf("\n\t2.Deposit Money ");
printf("\n\t3.View Balance ");
printf("\n\t0.Exit ");
printf("\n**********************************");
printf("\nPlease Type Your Choice Using 0-3");
printf("\nThen Hit Enter: ");
scanf("%d", &Choice);
return Choice;
} //getchoice
/*============================withdraw=*/
double withdraw (int Choice, int Balance)
{
// Local Declarations
double amount;
// Statements
printf("Funds:%d", &Balance);
printf("\nPlease Enter How Much You Would Like To Withdraw: ");
scanf("%f", &amount);
Balance = Balance - amount;
return Balance;
} //withdraw
/*============================Deposit=*/
double deposit (int Choice, int Balance)
{
// Local Declarations
double amount;
// Statements
printf("Funds:%d", &Balance);
printf("\nPlease Enter How Much You Would Like To Deposit: ");
scanf("%f", &amount);
Balance = Balance + amount;
return Balance;
} //Deposit
/*============================VBalance=*/
int VBalance (int Choice, int Balance)
{
// Statements
printf("\nYour Current Funds:%d", &Balance);
printf("\nThank Your For Viewing");
return 0;
}
First: Enable compiler warnings. If you use gcc, add -Wall to the command line. If you use an IDE the option to turn on warnings should be in the compiler settings.
When you compile with warnings you will find that you have some problems with your use of printf and scanf. Fix those!
Next you have the problem with Balance in main not getting updated. C uses call by value which means that the changes you make to a function argument are not visible in the calling function. To work around that you could declare the balance parameters as pointers and pass the address of Balance. Or you could return the new Balance, just like you do in your code. The only thing you forgot is to store the new value to Balance in main.
Changed line in main:
Balance = process(Choice, Balance);
Changed process:
double process(int Choice, int Balance)
{
// Declarations
// Statements
switch (Choice)
{
case 1: Balance = withdraw(Choice, Balance); // Changed line
break;
case 2: Balance = deposit(Choice, Balance); // Changed line
break;
case 3: Balance = VBalance(Choice, Balance); // Changed line
break;
case 0: exit;
break;
deafult: printf("Sorry Option Not Offered");
} // switch
return Balance; // Changed line
}
Third: Balance is declared an int, but you sometimes use double. You should choose one type and stick to it. Due to the nature of floating point numbers it is actually recommended that an integral type is used for money.

trouble with saving and printing data with arrays

I'm having a slight bit of trouble with saving data into arrays. Most of the code works as required, but what I'm having trouble doing is saving the data, such as deposits, withdrawals, transfers, into an array for them all to be printed out at the end. Two main problems are occurring.
1. Either nothing has been entered (which is completely acceptable) and then random digits are being output. 2. If something has been entered during a loop, such as a deposit, and then the user decides to enter another deposit before the loop is finished, the output will only be the last entry (whereas I want it to be two separate outputs). I can't seem to think of a way around these problems so any help is appreciated!
#include <stdio.h>
#include <stdlib.h>
//global variable for the overdraft
float OVERDRAFT = -1000;
//function to determine interest rate for users deposit
//return the interest rate to be used in the total() function
float interest(float money)
{
float int_rate;
if (money < 0 && money >= -100)
{
int_rate = 1.2f;
}
else if (money >= 0 && money < 100)
{
int_rate = 1.1f;
}
else if (money >= 100 && money < 200)
{
int_rate = 1.5f;
}
else if (money >= 200 && money < 500)
{
int_rate = 1.8f;
}
else if (money >= 500)
{
int_rate = 1.9f;
}
else if (money < -100 && money >= -500)
{
int_rate = 1.4f;
}
else if (money < -500 && money >= -1000)
{
int_rate = 1.8f;
}
return int_rate;
}
//function to calculate final amount with interest applied
//uses previous interest() function to calculate final amount by multiplying them together
//if the amount is less than -1000 (overdraft) then the OVERDRAFT value of -1000 is returned
//else, returns the normal amount
float total(float x)
{
float int_func;
int_func = interest(x);
float amount = x * int_func;
if (amount < OVERDRAFT)
{
return OVERDRAFT;
}
else
{
return amount;
}
}
//function that checks if user enters an amount greater than 0
//returns an integer dependent on this
//this is used in main function to determine if money can be added to the account (0 means yes, -1 means no)
float add_money(float *Account, float Amount)
{
if (Amount > 0)
{
return 0;
}
else
{
return -1;
}
}
float take_money(float *Account, float Amount)
{
if (Amount > 0)
{
return 0;
}
else
{
return -1;
}
}
//function to be used for the transfer section in the main function
//finds out if users input (multiplied by interest) is positive
//if it is, 0 is returned which can be used later
float transfer(float y)
{
float int_func;
int_func = interest(y);
float amount = y * int_func;
if (amount >= 0)
{
return 0;
}
else
{
return -1;
}
}
//creates a sentinel while loop so that user can exit it if they press 0, or reloops if they enter any other number
float main(void)
{
float sentinel = 1;
while (sentinel != 0)
{
//asks the user to enter amount they wish to deposit in both main and savings accounts
//asks the user how many months they want to simulate (3 months with a starting deposit of £50 will result in £55, £60.50, £66.55)
float deposit, add, take, savings, tran;
int count, amount, answer;
float x, dep[51], withd[51];
float m_to_s[51], s_to_m[51];
printf("Initial deposit for your main account:\n");
scanf_s("%f", &deposit);
while (deposit < OVERDRAFT)
{
//while loop to make sure user enters positive number for main account
printf("ERROR: You have an overdraft limit of \x9C%.0f.\nPlease enter a greater initial deposit:\n", (OVERDRAFT* -1));
scanf_s("%f", &deposit);
}
printf("Initial deposit for your savings account:\n");
scanf_s("%f", &savings);
while (savings < 0)
{
//while loop to make sure user enters positive number for savings account
printf("ERROR: Please enter a positive value:\n");
scanf_s("%f", &savings);
}
printf("Amount of months to simulate:\n");
scanf_s("%d", &amount);
while (amount <= 0)
{
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%d", &amount);
}
//for loop with a switch statement to allow user to choose option from main menu
//user can deposit money, withdraw money, transfer money, and move to the next month with interest applied from the menu
for (count = 1; count <= amount; count++)
{
printf("\nPlease choose one of the below options:\n");
printf("1: Deposit money (Main account only)\t");
printf("2: Withdraw money (Main account only)\n");
printf("3: Transfer money\t\t\t");
printf("4: Balance next month (with interest)\n");
scanf_s("%d", &answer);
while (answer <= 0 || answer >= 5)
{
//while loop to ensure user chooses one of the 4 options
printf("\nPlease choose one of the below options:\n");
printf("1: Deposit money (Main account only)\t");
printf("2: Withdraw money (Main account only)\n");
printf("3: Transfer money\t\t\t");
printf("4: Balance next month (with interest)\n");
scanf_s("%d", &answer);
}
//main menu
switch (answer)
{
//option 1 to deposit more money
//adds money to the account if 0 was returned in add_money() function
//errors given if -1 was returned in add_money() function
case 1: printf("\nYou chose to make a deposit\n");
printf("Amount to deposit:\n");
scanf_s("%f", &dep[count]);
add = add_money(&x, dep[count]);
while (dep[count] <= 0)
{
//while loop to ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &dep[count]);
}
if (dep[count] > 0)
{
deposit = deposit + dep[count];
printf("Main account balance: \x9C%.2f.\n", deposit);
//reduces count by 1 so that it outputs correctly at end
count -= 1;
}
else
{
printf("ERROR: You entered an invalid amount.\n");
count -= 1;
}break;
//option 2 to withdraw money
//reduces count by 1 so that the program doesn't end sooner than the user wanted
case 2: printf("\nYou chose to make a withdrawal\n");
printf("Amount to withdraw:\n");
scanf_s("%f", &withd[count]);
take = take_money(&x, withd[count]);
while (withd[count] <= 0)
{
//while loop to ensure user enters value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &withd[count]);
}
if (withd[count] > 0)
{
//sets deposit variable to a new value according to the users input (may be reverted back in the if statement if it goes over overdraft)
deposit = deposit - withd[count];
if (deposit < OVERDRAFT)
{
//reverts the recentl deposit variable as it will not be possible as the user will go over the overdraft
printf("ERROR: You can't withdraw that much as you will go over your overdraft limit\n");
deposit = deposit + withd[count];
count -= 1;
break;
}
else if (deposit > OVERDRAFT)
{
printf("Main account balance: \x9C%.2f.\n", deposit);
count -= 1;
break;
}
}
else
{
printf("ERROR: You entered an invalid amount\n");
count -= 1;
}break;
//option 3 to transfer money from one account to another
case 3: printf("\nYou chose to transfer money\n");
printf("Please choose an option:\n");
printf("1: Transfer from Main account to Savings account\n");
printf("2: Transfer from Savings account to Main account\n");
int option;
scanf_s("%d", &option);
while (option < 1 || option > 2)
{
//while loop to ensure user chooses one of the two options
printf("Please choose an option:\n");
printf("1: Transfer from Main account to Savings account\n");
printf("2: Transfer from Savings account to Main account\n");
scanf_s("%d", &option);
}
//switch inside a switch
switch (option)
{
case 1: printf("\nYou chose to transfer money from your Main account to your Savings account\n");
printf("Please enter how much to transfer:\n");
scanf_s("%f", &m_to_s[count]);
tran = transfer(m_to_s[count]);
while (m_to_s[count] <= 0)
{
//while loop to ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &m_to_s[count]);
}
//if statement that will be run if user enters value greater than 0
if (m_to_s[count] > 0)
{
savings = savings + m_to_s[count];
deposit = deposit - m_to_s[count];
if (deposit >= OVERDRAFT)
{
//prints out both balances of accounts after the transfer
printf("\nMain account balance %.2f\n", deposit);
printf("Savings account balance: %.2f\n", savings);
count -= 1;
}
else
{
printf("ERROR: You can't transfer that much as you don't have a large enough overdraft on your Main account\n\n");
//if user enters an incorrect amount (because overdraft is reached), variables are restored so that end output is correct
savings = savings - m_to_s[count];
deposit = deposit + m_to_s[count];
count -= 1;
}
}break;
//transfer money from savings to main
case 2: printf("\nYou chose to transfer money from your Savings Account to your Main account\n");
printf("Please enter how much to transfer:\n");
scanf_s("%f", &s_to_m[count]);
tran = transfer(s_to_m[count]);
while (s_to_m[count] <= 0)
{
//while loop so ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &s_to_m[count]);
}
//if statement that will be run if user enters a value greater than 0
if (s_to_m[count] > 0)
{
//adjusts balances using users entered value (these variables may be reverted in the else statement if the savings go lower than 0 as there is no overdraft)
savings = savings - s_to_m[count];
deposit = deposit + s_to_m[count];
if (savings >= 0)
{
//prints out current balances
printf("\nMain account balance: %.2f\n", deposit);
printf("Savings account balance: %.2f\n", savings);
count -= 1;
}
else
{
//error if user tries to transfer too much money out of their savings account because there is no overdraft
printf("ERROR: You can't transfer that much as you don't have an overdraft on your Savings account\n\n");
savings = savings + s_to_m[count];
deposit = deposit - s_to_m[count];
count -= 1;
}break;
}
else
{
printf("ERROR\n\n");
count -= 1;
}break;
}break;
//option 4 to move onto the next month (with interest applied to both accounts)
case 4:
deposit = total(deposit);
savings = total(savings);
printf("\nYou chose to show account balances (with interest) for the next month\n");
printf("Month %d Main account balance: \x9C%.2f.\n", count, deposit);
printf("Month %d Savings account balance: \x9C%.2f\n", count, savings);
}
}
for (count = 1; count <= amount; count++)
{
//sting array
//prints out transactions
//NOT WORKING CORRECTLY
printf("\nDeposit %d: %.2f\n", count, dep[count]);
printf("Withdrawal %d: %.2f\n", count, withd[count]);
printf("Transfer Main to Savings %d: %.2f\n", count, m_to_s[count]);
printf("Transfer Savings to Main %d: %.2f\n", count, s_to_m[count]);
}
//if user enters 0, while loop is broken
//if user enter anything other than 0, loop reloops
printf("\nTo terminate program, enter '0'.\n");
printf("To run program again, enter any other number.\n");
scanf_s("%f", &sentinel);
}
return 0;
}
the code is long and really hard to go through but if I did understand it corectly you need to:
Initialize all the variables. Set them to zero or something accaptable for you.
you are using dep[count] but you always do count -= 1; after that. Try to look at that.

Scanf with pointers in C

I have some code, but I'll shorten it to show only the relevant parts.
// Displays the list of user’s options available
//Displays the user’s selections and sets the value of the choice
void mainMenu(int *choice);
//Displays the types of account they would like to access and sets the
//value of the chosen account type
void AccountMenu(char *typeAcct);
//Prompts the user for the amount of their deposit and updates the selected account
void DepositMoney(double *currBal);
//Asks the user if they want another transaction
void Repeat(char * doAgain);
int main(){
int choice = 0;
char repeat = 'y';
double checkBal = 575.0,
saveBal = 3750.0,
credBal = 450.0;
char typeAcct;
while(repeat!='n'){
mainMenu(&choice); //get action from user
AccountMenu(&typeAcct); //get account to perform action on from user
switch (choice){
case 1:
switch (typeAcct){
case 'c':
DepositMoney(&checkBal);
break;
case 's':
DepositMoney(&saveBal);
break;
case 'r':
DepositMoney(&credBal);
break;
} //case 1
break;
}
Repeat(&repeat);
repeat = tolower(repeat);
}
}
// Displays the list of user’s options available
//Displays the user’s selections and sets the value of the choice
void mainMenu(int *choice){
printf("Bank Program\n\n");
printf("Please enter your choice:\n");
printf("[1] Deposit\n");
printf("[2] Withdraw\n");
printf("[3] Balance Inquiry\n\n >> ");
scanf(" %d", choice);
}
//Displays the types of account they would like to access and sets the
//value of the chosen account type
void AccountMenu(char *typeAcct){
char choice;
printf("Please enter your choice:\n");
printf("[C] Checking\n");
printf("[S] Savings\n");
printf("[R] Credit\n\n >> ");
scanf(" %c", &choice);
*typeAcct = tolower(choice);
}
//Prompts the user for the amount of their deposit and updates the selected account
void DepositMoney(double *currBal){
printf("Depositing money.\nHow much would you like to deposit?\n\n >> ");
double amount = 0; //deposit amount
scanf(" &f", &amount);
*currBal = *currBal + amount;
}
void Repeat(char * doAgain){
printf("Would you like to perform another transaction? (y/n)\n\n >> ");
scanf(" &c", doAgain);
}
When I execute this code, it runs mostly fine. For example, if I enter "1" for mainMenu and "c" for AccountMenu, choice and typeAcct are both indeed set to "1" and "c" respectively.
The problem doesn't seem to be with the loop. I've tried taking out the loop and only running it once and it still doesn't work. What happens is that after inputting the amount of money I would like to deposit, the value of the variable isn't updated and mainMenu and AccountMenu are run again (even when DepositMoney is the last line of code in the main function and there is no loop). Why does this happen?
1) Incorrect scanf() usage
double amount = 0;
// scanf(" &f", &amount);
scanf(" %lf", &amount);
// scanf(" &c", doAgain);
scanf(" %c", doAgain);
2) Insure your compiler warning are fully enabled. This is the most important bit as most problems are quickly identified this way.
3) Always check the return value of scanf(). BTW, the leading space in " %f" is not needed as "%f" scans over leading white-space anyways. Good though, to have with " %c".
if (scanf("%lf", &amount) != 1) Handle_Error();
4) tolower() take an int. In the rare siuation where a user enters a char in the range \x80 to \xFF, the conversion of char to int is a sign extend and likely a negative number. Unfortunately, this does not work for tolower() which is well defined for 0 to 255 and EOF, but not other negative values.
// repeat = tolower(repeat);
repeat = tolower((unsigned char) repeat);
...
// *typeAcct = tolower(choice);
*typeAcct = tolower((unsigned char) choice);

Resources