Passing the value from this function - c

#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.

Related

In checkout function g_tot calculation brings garbage value

In this code at checkout function g_tot calculation brings garbage value. I think its because I'm calculating two variables from another two functions, but I don't know how to fix it. There's another error in restaurant function in if condition if I enter value more than 8 it'll bring garbage value to tot. But the most important one is
#include<stdio.h>
#include<conio.h>
// Global variables
int room,answr,days=0;
char name[20],choose;
int i=0,tot=0,p_tot=0,g_tot=0,z=0;
int p_price[2][5]={4000,10000,20000};
void screenheader()
{
printf("\n ::::::::::::::::::::::::::::::::::::::");
printf("\n :: ::");
printf("\n :: ############################ ::");
printf("\n :: # # ::");
printf("\n :: # WELCOME # ::");
printf("\n :: # TO # ::");
printf("\n :: # SURF HOTEL # ::");
printf("\n :: # # ::");
printf("\n :: ############################ ::");
printf("\n :: ::");
printf("\n ::::::::::::::::::::::::::::::::::::::");
}
void check_in()
{
int contact_No[20],NIC[10];
char first_name[10],last_name[10],Country[10];
system("cls");
screenheader();
printf("\n1. Packages");
printf("\n2. Room Allocation");
printf("\n3. Back\n\n");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
system("cls");
printf("\n\n\nPer 2 Persons");
printf("\n\t\tPackage Name >>>> Couple");
printf("\n\t\tRs.4000/= per day");
printf("\n\t\tBed >>>> 1");
printf("\n\t\t *Tv Available");
printf("\n\n\n\n\t\t\nPer 4 Persons\n\t\tPackage Name >>>>
Family");
printf("\n\t\tRs.10,000/= per day");
printf("\n\t\tBed >>>> 2");
printf("\n\t\t*Tv Available \n\t\t*A/C \n\t\t*WIFI");
printf("\n\n\n\nPer 8 Persons\n\t\tPackage Name >>>> Deluxe");
printf("\n\t\tRs.20,000/= per day");
printf("\n\t\tBed >>>> 3 Large ");
printf("\n\t\t *Tv Available \n\t\t*A/C \n\t\t*WIFI\n\t\t*Local
Travel Guide\n\t\t*Balcony with a view\n\t\t*Writing desk");
printf("\n\n*Press 1 to go back");
getch();
check_in();
break;
}
case 2:{
printf("What package do you want?");
scanf(" %d",&i);
p_tot=p_tot+p_price[i-1];
if(i == 1)
{
printf("You have selected Couple package");
}
else if (i == 2)
{
printf("You have selected Family Package ");
}
else if (i == 3)
{
printf("You have selected Deluxe package");
}
else
{
printf("\n\nWrong input, please refer to packages and try
again.\nPress Enter to select another package");
getch();
check_in();
}
printf("\nEnter First Name:\n");
scanf(" %s",&first_name);
printf("Last Name:\n");
scanf(" %s",&last_name);
printf("How many days do you want to stay?");
scanf(" %d",&days);
printf("Enter your Country:");
scanf(" %s",&Country);
printf("Enter your NIC No:");
scanf(" %d",&NIC);
printf("Enter your Contact No:");
scanf(" %d",&contact_No);
printf("Hello %s %s you have booked a Room for
%d",&first_name,&last_name,days);
getch();
system("cls");
int main();
}
case 3: main();
}
}
void restaurant()
{
int fc[6];
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("Press Enter To Continue To The Restaurant ");
getchar();
system("cls");
printf("\n\n\n\n\n\t *********");
printf("\n\t MENU CARD");
printf("\n\t *********\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\tRs. %d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER FOOD
: ");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
main();
break;
}
case 1:do
{
printf("\n\nENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8)
{
printf("Invalid food code\n");
}
tot=tot+price[z-1];
printf("total so far is Rs.%d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c", &ans);
} while(ans=='y'|| ans=='Y');
printf("\n\nYour bill is Rs.%d",tot);
printf("\nYour bill will be added to the total bill at checkout");
printf("\n\nPress Enter to go back to main menu");
getch();
system("cls");
main();
}
}
void check_out()
{
system("cls");
screenheader();
printf("\n\nAre you sure you want checkout (Y/N)");
scanf(" %c",&choose);
if(choose=='n' || choose=='N')
{
main();
}
else if(choose== 'Y' || choose=='y')
{
system("cls");
screenheader();
g_tot=p_tot+tot;
printf("Total");
printf("%d",g_tot);
}
}
int main()
{
screenheader();
printf("\n\n\nPress Enter To Continue");
getchar();
system("cls");
screenheader();
printf("\n\n\n\n\t\t ************* \n");
printf("\t\t * MAIN MENU * \n");
printf("\t\t ************* \n\n\n");
printf("\t\t\t01. Check In \n");
printf("\t\t\t02.Restaurant\n");
printf("\t\t\t03.Checkout \n");
printf("\n\t\t\t04.Exit");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
check_in();
break; }
case 2:{
restaurant();
break; }
case 3: {
check_out();
}
}
return 0;
}
if condition if I enter value more than 8 it'll bring garbage value to tot.
This is as expected. When z > 8, code attempts to access outside price[] range. Result: undefined behavior (UB). The prior if (z < 1 || z > 8) did not steer code away from price[z - 1]. Rest of code including g_tot = p_tot + tot; is now questionable.
int price[8] = {180, 120, 65, 55, 70, 70, 110, 200};
...
if (z < 1 || z > 8) {
printf("Invalid food code\n");
}
tot = tot + price[z - 1]; // UB here
...
g_tot = p_tot + tot;
Do not access price[z - 1] unless z in the range [1...8].
Other problems exist: Best to enable all compilers warnings and seem them (12+) yourself.

Saving data in files in c

I am working on this cinema reservation project !! 2 problems i m facing here is with data saving.
1) : when i close the program and try to register a new user the login information of previous registered user deletes Even though i am opening file in "a+" mode. but if i directly log in with the already registered user it works. the thing is i am not able to register more than 1 user at a time.
2) : When i close the program and logged in again the information of user reservation deletes. i want to save the user's reservation information too.
How can I solve this ?
struct login
{
char fname[100];
char lname[100];
char username[20];
char password[20];
};
#include <stdio.h>
#define RVALUE 5
#define CVALUE 10
int i, j;
void DisplaySeats(void);
void ReserveSeats(void);
void ChooseSeat(void);
void CancelSeat(void);
void CheckCancelSeat(void);
void menu(void);
int Seats[RVALUE][CVALUE];
void registration();
void login();
int main()
{
int c;
int choice, menu;
printf("Welcome to our small Cinema!!!\n");
printf("\n");
//DisplaySeats();
printf("\n1 : register!!!\n");
printf("2 : login!!!\n");
printf("3 : quit\n");
printf("Enter your choice : \n");
scanf("%d",&c);
switch (c)
{
case 1:
registration();
break;
case 2:
login();
break;
case 3:
printf("Thankyou for Choosing our small Cinema !! \n");
getch();
exit(1);
default :
system("CLS");
printf("Enter a valid number !!\n");
main();
}
getch();
}
void registration()
{
FILE *log;
log = fopen("login.txt", "a+");
struct login l;
printf("\nEnter first name : ");
scanf("%s", &l.fname);
printf("\nEnter last name : ");
scanf("%s", &l.lname);
printf("\nEnter your Username : ");
scanf("%s", &l.username);
printf("\nEnter your password : ");
scanf("%s", &l.password);
fwrite(&l, sizeof(l), 1, log);
fclose(log);
printf("\nYou are successfully registered!!");
printf("\nYour UserId is %s and your password is %s", l.username, l.password);
printf("\nNow login with your username and password!!");
printf("\nPress any key to continue ...");
getch();
system("CLS");
main();
}
void login()
{
char username[100];
char password[100];
FILE *log;
struct login l;
log = fopen("login.txt", "r");
if (log == NULL)
{
printf("FILE NOT FOUND!!!");
exit(1);
}
printf("\nUserID : ");
scanf("%s", &username);
printf("\nPassword : ");
scanf("%s", &password);
while (fread(&l, sizeof(l), 1, log));
{
if (strcmp(username, l.username) == 0 && strcmp(password, l.password)==0)
{
system("CLS");
printf("\nYou are successfully logged in !!\n");
menu();
}
else
{
printf("\nYour UserID or password is incorrect !!\n");
printf("Press any key to continue ...\n");
getch();
system("CLS");
login();
}
}
fclose(log);
}
void ChooseSeat(void)
{
int row, col,k;
printf("Which row do you want to choose? : ");
scanf("%d", &row);
printf("Which seat do you want to select? : ");
scanf("%d", &col);
if (row > RVALUE || col > CVALUE)
{
printf("Wrong Entry !! Try again\n");
ChooseSeat();
}
else if (Seats[row - 1][col - 1] != 0)
{
printf("Seat is already reserved try again !!\n");
ChooseSeat();
}
else
{
Seats[row - 1][col - 1] = 1;
printf("Congratulations!! Reservation Completed!!!\n");
DisplaySeats();
printf("\nPress any key to go to main menu!!");
getch();
system("CLS");
main();
}
}
void ReserveSeats(void)
{
int NoOfSeats,i;
printf("How many seats do you want to reserve?\n");
scanf("%d", &NoOfSeats);
DisplaySeats();
for (i = 1; i <= NoOfSeats; i++)
{
ChooseSeat();
}
}
void DisplaySeats(void)
{
printf("\t \t Seats\n");
printf("\t 1 2 3 4 5 6 7 8 9 10\n");
for (i = 0; i < RVALUE; i++)
{
printf("Rows %d : ", i + 1);
for (j = 0; j < CVALUE; j++)
printf("%d ", Seats[i][j]);
printf("\n");
}
printf("\n");
}
void CheckCancelSeat(void)
{
while (1)
{
for (i = 0; i < RVALUE; i++)
{
for (j = 0; j < CVALUE; j++)
{
if (Seats[i][j] == 0)
{
printf("There is no reserved seat available!!\n");
break;
}
else
{
CancelSeat();
}
break;
}
break;
}
system("CLS");
break;
}
}
void CancelSeat(void)
{
int r, c;
printf("\nWhich row do you want to cancell ? : ");
scanf("%d", &r);
printf("\nWhich column do you want to cancell ? : \n");
scanf("%d", &c);
if (Seats[r - 1][c - 1] != 0)
{
Seats[r - 1][c - 1] = 0;
printf("Your Seat is Cancelled !!\n");
system("CLS");
}
else
{
printf("Wrong Entry !!\n");
CancelSeat();
}
}
void menu(void)
{
int choice;
DisplaySeats();
printf("1 : reserve a seat\n");
printf("2 : cancell a seat\n");
printf("3 : Main Menu\n");
printf("Enter your choice : \n");
scanf("%d", &choice);
system("CLS");
switch (choice)
{
case 1:
ReserveSeats();
break;
case 2:
CheckCancelSeat();
break;
case 3:
main();
break;
default:
printf("Please enter a valid choice!!");
menu();
break;
}
}
The problem is that it is very difficult to save more than one structure to a binary file.
Note: Binary files do not have the file extension ".txt" but z. ".Bin", ".dat" or the like; Sometimes binary files are saved even without file extension.
I think you try to "spam" the password in the binary file (encrypt). Unfortunately, I have to tell you that this does not work. If you open the file with a text editor you will see the password.
I would suggest you save the data as a text file and then read the data step by step.
Also, you did not have all the functions declarated.
There are implicit declarations. This can lead to errors for larger programs. For a few, the solution would be to include stdlib.h.
If you want to save a file the following night please use the mode Subfix "b" z. Eg "a + b".
A few helpful links are possible:
http://www.cplusplus.com/reference/cstdio/fopen/
http://www.cplusplus.com/reference/cstdio/fwrite/
Reading/Writing a structure into a binary file
Although I could not solve the problems, but I hope I could help anyway.
If you still want to save the structures in a binary file, you can read this on the Internet (I just say Google).
For example, if you want to encrypt something with C, you can search for a crypt library or something similar.

Check for bad practices/improvements

I'm relatively new to coding yet not completely inexperienced. Working on a school assignment regarding financial calculators. Would be great if any of you could take a look at my code for bad practices/possible improvements etc.
I did add a 'animated' startup (with a lot of printf to show "financial calculator" but couldn't fit it in, is it a good idea to do something like that?)
option_2 and option_4 are left as placeholders for the time being while my group works on other 2 calculators.
//ASSIGNMENT_041118
//libraries
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <signal.h>
//files
//colours
#define ANSI_COLOR_BLACK "\x1b[30m"
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_WHITE "\x1b[37m"
#define ANSI_COLOR_BBLACK "\x1b[90m"
#define ANSI_COLOR_BRED "\x1b[91m"
#define ANSI_COLOR_BGREEN "\x1b[92m"
#define ANSI_COLOR_BYELLOW "\x1b[93m"
#define ANSI_COLOR_BBLUE "\x1b[94m"
#define ANSI_COLOR_BMAGENTA "\x1b[95m"
#define ANSI_COLOR_BCYAN "\x1b[96m"
#define ANSI_COLOR_BWHITE "\x1b[97m"
#define ANSI_COLOR_RESET "\x1b[0m"
//function prototype declaration
int main_menu();
int login();
float compound();
float compound_calc(float n, float initial_savings, float rate, float time);
float option_2();
float mortgage();
float option_4();
int main()
{
system("color 0F");
login();
return (0);
}
int login()
{
char username[20];
char password[20];
int l_option;
printf("=========================================================================================================\n");
printf("Enter your username (case sensitive): ");
scanf("%s", &username);
printf("\nEnter your password (case sensitive): ");
scanf("%s", &password);
if (strcmp(username, "user") == 0)
{
if (strcmp(password, "0000") == 0)
{
system("cls");
return main_menu();
}
else
{
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR - WRONG PASSWORD\n"ANSI_COLOR_RESET);
do {
printf("---------------------------------------------------------------------------------------------------------\n");
printf("[1]Retry\n[0]Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &l_option);
switch (l_option)
{
case 1:
system("cls");
return login();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("EXIT\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED "INVALID OPTION - CHOOSE AGAIN\n" ANSI_COLOR_RESET);
break;
}
} while (l_option != 1 && l_option != 0);
}
}
else
{
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR - USER DOESN'T EXIST\n"ANSI_COLOR_RESET);
do {
printf("---------------------------------------------------------------------------------------------------------\n");
printf("[1]Retry\n[0]Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &l_option);
switch (l_option)
{
case 1:
system("cls");
return login();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("EXIT\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED "INVALID OPTION - CHOOSE AGAIN\n" ANSI_COLOR_RESET);
break;
}
} while (l_option != 1 && l_option != 0);
}
}
int main_menu()
{
int option_main;
do {
printf("=========================================================================================================\n");
printf("Choose an option:\n"); //tells user to select an option
printf("---------------------------------------------------------------------------------------------------------\n");
printf(ANSI_COLOR_BGREEN"[1] <Savings Calculator - Compounded Interest> \n"ANSI_COLOR_RESET); //displays options
printf(ANSI_COLOR_BMAGENTA"[2] <place_holder_2> \n"ANSI_COLOR_RESET);
printf(ANSI_COLOR_BYELLOW"[3] <Mortage calculator> \n"ANSI_COLOR_RESET);
printf(ANSI_COLOR_BCYAN"[4] <place_holder_3> \n"ANSI_COLOR_RESET);
printf("\n[0] <Exit system>\n");
printf("=========================================================================================================\n");
scanf("%d", &option_main); //accepts input for function selection
printf("=========================================================================================================\n");
system("cls");
switch (option_main) //switch case for main option
{
case 1:
{
compound();
break;
}
case 2:/*option_2*/
{
option_2();
break;
}
case 3:/*option_3*/
{
mortgage();
break;
}
case 4:/*option_4*/
{
option_4();
break;
}
case 0:/*exit*/
{
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
}
default:
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);
break;
}
}
} while (option_main != 1 && option_main != 2 && option_main != 3 && option_main != 4 && option_main != 0);
return (0);
}
float compound() //compound_interest_calculation_self_defined function
{
int compound_type, ci_option;
float n, initial_savings, rate, time, final_savings;
do {
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BGREEN"<Savings Calculator - Compounded Interest>\n"ANSI_COLOR_RESET); //displays option selected (Savings Calculator - Compounded Interest)
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter compound type:\n"); //Prompts user to choose
printf("[1] Monthly\n[2] Quarterly\n[3] Semiannually\n[4] Annually\n\n[9]Return to menu\n[0] Exit\n");//displays options
printf("=========================================================================================================\n");
scanf("%d", &compound_type); //accepts input for option selection
printf("=========================================================================================================\n");
system("cls");
switch (compound_type) //internal switch case for compounded interest calculator
{
case 1: /*monthly*/
n = 12;
printf("=========================================================================================================\n");
printf("<Monthly compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM "); //prompts user for initial saving amount (principle)
scanf("%f", &initial_savings); //accepts input for initial savings
/*printf("Please enter monthly deposit: RM "); //prompts user input for monthly deposit
scanf("%f", &monthly_deposit); */ //accepts input for monthly deposit
printf("Please enter interest rate (decimal): "); //prompts user input for interest rate
scanf("%f", &rate); //accepts input for interest rate
printf("Please enter time (year): "); //prompts input for saving duration
scanf("%f", &time); //accepts input for saving duration
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings); //dispays final savings amount
printf("=========================================================================================================\n");
break;
case 2: /*quarterly*/
n = 4;
printf("=========================================================================================================\n");
printf("<Quarterly compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings);
printf("=========================================================================================================\n");
break;
case 3: /*semiannually*/
n = 2;
printf("=========================================================================================================\n");
printf("<Semiannual compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings);
printf("=========================================================================================================\n");
break;
case 4: /*annually*/
n = 1;
printf("=========================================================================================================\n");
printf("<Annual compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f\n", final_savings);
printf("=========================================================================================================\n");
break;
case 9: /*return to menu*/
return main_menu();
break;
case 0: /*exit*/
printf("=========================================================================================================\n");
printf("<EXIT> \n");
printf("=========================================================================================================\n");
exit(0);
default:/*any other input*/
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);//When user inputs invalid option for compound type
}
} while (compound_type != 0 && compound_type != 1 && compound_type != 2 && compound_type != 3 && compound_type != 4 && compound_type != 9);
do
{
printf("[1]Back to compound interest calculator\n[9]Return to menu\n[0] Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &ci_option);
switch (ci_option)
{
case 1:
system("cls");
return compound();
break;
case 9:
system("cls");
return main_menu();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:/*any other input*/
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
}
} while (ci_option != 1 && ci_option != 9 && ci_option != 0);
return(0);
}
float compound_calc(float n, float initial_savings, float rate, float time)
{
float CI;
CI = (initial_savings*(pow((1 + rate / n), (n * time))));
return (CI);
}
float option_2()
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BMAGENTA"<place_holder_2> selected \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
return(0);
}
float mortgage()
{
float house_price, down_percentage, interest_rate, monthly_payment, r, p;//variables declaration
int loan_period, n,m_option;
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BYELLOW"<Home mortgage calculator>\n"ANSI_COLOR_RESET); //displays option selected (Savings Calculator - Compounded Interest)
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Insert property price: RM ");//prompt input
scanf("%f", &house_price);//get input
printf("Insert down percentage (decimal): ");
scanf("%f", &down_percentage);
printf("Insert loan period (Years): ");
scanf("%d", &loan_period);
printf("Insert interest rate (decimal):");
scanf("%f", &interest_rate);
r = interest_rate / 12;
n = loan_period * 12;
p = house_price - house_price *down_percentage;
monthly_payment = p *(r*pow((1 + r), n)) / (pow((1 + r), n) - 1);//calculate monthly payment //NOTE:MOVE TO SELF DEFINED FUNCTION
printf("\nYour monthly payment is %.2f \n", monthly_payment);//display output
do
{
printf("=========================================================================================================\n");
printf("[3]Recalculate\n[9]Return to menu\n[0] Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &m_option);
switch (m_option)
{
case 3:
system("cls");
return mortgage();
break;
case 9:
system("cls");
return main_menu();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:/*any other input*/
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR: INVALID OPTION \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
}
} while (m_option != 3 && m_option != 9 && m_option != 0);
return (0);
}
float option_4()
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BCYAN"<place_holder_4> selected \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
return(0);
}
Replace your "scanf();" to "fgets();"
char *fgets(char *str, int n, FILE *stream)
Example:
#include <stdio.h>
#include <string.h>
char Name[50];
int main(){
printf("What is your name?\n> ");
fgets(Name,50,stdin); //Gets user input from stdin (not from file)
/* But the problem is that fgets also includes '\n' so we put: */
Name[strcspn(Name,"\r\n")]=0; //Removes '\n'
printf("Your name is: <%s>\n",Name);
return 0;
}

My do while loop is not looping correctly

I might be giving more than enough but long story short I am working on an ATM machine program and I am trying to put the "switch" statement in the main function inside a loop so the user can get more transactions.
I am running into a problem where I would deposit 100 but then when I check the balance it is still at 0. I know everything else works fine but that loop is killing me, I would appreciate any help!
Don't mind all of the extra stuff it is just there to give an idea on what i am working on
int main ()
{
char option;
float balance ;
int count = 1;
option = displayMenu();
do
{
switch (option)
{
case 'D':
getDeposit(balance);
main();
count++;
break;
case 'W':
getWithdrawal(balance);
main();
count++;
break;
case 'B':
displayBalance(balance);
main();
count++;
break;
case 'Q':
printf("Thank you!");
break;
main();
}
} while ( count <= 5);
return 0;
}
char displayMenu()
{
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c" , &option);
return option;
}
float getDeposit(float balance)
{
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f" , &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance)
{
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f" , &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance)
{
printf("\n Your current balance is %f " , balance);
}
You're recursively calling main() on every iteration of the loop. Just remove this call, and you should be good to go.
You'll also need to assign the return values of your functions to balance, otherwise they won't be able to affect its value.
There are a number of issues with this code... Here are my main pointers (but not all of them, I'm just answering the question):
You're calling main over and over again, for simplicity, you could consider this as restarting the application every time (except for stack issues, that I'm ignoring and other nasty side effects).
You didn't initialize the balance (and friends) variables. They might contain "junk" data.
You're ignoring the return values from the functions you use. If you're not using pointer, you should use assignment.
Your menu printing function is out of the loop... I doubt if that's what you wanted.
Here's a quick dirty fix (untested):
int main() {
char option;
float balance = 0;
int count = 1;
do {
option = displayMenu(); // moved into the loop.
switch (option) {
case 'D':
balance = getDeposit(balance);
count++;
break;
case 'W':
balance = getWithdrawal(balance);
count++;
break;
case 'B':
balance = displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
break;
}
} while (count <= 5);
return 0;
}
char displayMenu(void) {
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c", &option);
return option;
}
float getDeposit(float balance) {
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f", &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance) {
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f", &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance) {
printf("\n Your current balance is %f ", balance);
}
Good Luck!
I think the main problem is the update of the switch control variable outside the loop.
Reacting to "Q" with ending is somewhat necessary... then only allowing 5 becomes unneeded.
I fixed several other things, too; and provided comments on them.
And I improved testability a little (5->6). I kept the counting, just extended to 6, in order to allow a complete test "D 100 , B, W 50, B ,Q".
Nice design by the way, to return the balance from the functions, instead of using pointers or global variable. But you need to use the return value instead of ignoring it.
/* include necessary headers, do not skip this when making your MCVE */
#include <stdio.h>
/* prototypes of your functions,
necessary to avoid the "immplicitly declared" warnigns
when compiling "gcc -Wall -Wextra"; which you should
*/
char displayMenu(void);
float getDeposit(float balance);
float getWithdrawal(float balance);
void displayBalance(float balance);
/* slightly better header of main, with "void" */
int main (void)
{
char option;
float balance=0.0; /* initialise your main variable */
int count = 1;
/* your very important update of the switch control variable has been moved ... */
do
{
option = displayMenu(); /* ...here */
/* If you do not update your switch variable inside the loop,
then it will forever think about the very first command,
this explains most of your problem.
*/
switch (option)
{
case 'D':
balance=getDeposit(balance); /* update balance */
/* removed the recursive call to main(),
it is not needed as a solution to the problem that the program
always uses the first command (when updating inside the loop)
and otherwise just makes everything much more complicated and
risky.
*/
count++;
break;
case 'W':
balance=getWithdrawal(balance); /* update balance */
count++;
break;
case 'B':
displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
/* adding a way to get out of the loop,
using a magic value for the count,
this is a mehtod frowned upon by most,
but it minimises the changes needed to your
own coding attempt.
*/
count=0;
break;
}
} while ( (count <= 6)&&(count>0) ); /* additionally check for the magic "Q" value
check against count<=6, to allow testing D,B,W,B,Q */
return 0;
}
/* use explicitly empty parameter list for functions */
char displayMenu(void)
{
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c" , &option);
return option;
}
float getDeposit(float balance)
{
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f" , &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance)
{
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f" , &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance)
{
printf("\n Your current balance is %f " , balance);
}
you haven't changed the variable in main().
you can change the loop to this:
do
{
switch (option)
{
case 'D':
balance = getDeposit(balance);
count++;
break;
case 'W':
balance = getWithdrawal(balance);
count++;
break;
case 'B':
displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
break;
}
} while (count <= 5);

Menu system in c

I'm having serious trouble with my program it is supposed to provide a menu and do all the functions the code is pretty explanatory my problem is I only have visual studios which doesnt allow scanf and scanf_s and messes with things so I use online compilers but those are still iffy. Can any one help and give me some tips. I'm having trouble with the math and function to list accounts, some whiles are empty as well I wasn't sure if that was best to use. I'm relatively new to this forum. It also can't have struct and can only be in C :-(
#include <stdio.h>
char name[20];
float avail_bal;
void options();
void open();
void list();
void deposit();
void withdraw();
void exit();
int main(void)
{
char option;
while(1){
printf("****Banking System WELCOME****\n");
printf("Enter 1-5 of the following options: \n");
option = getchar();
scanf("%c\n", &option);
switch(option)
{
case '1': open();
break;
case '2': list();
break;
case '3': deposit();
break;
case '4': withdraw();
break;
case '5': return 0;
default: exit();
break;
}
}
return 0;
}
void options()
{
printf("1. Open Account\n");
printf("2. List Accounts\n");
printf("3. Deposit\n");
printf("4. Withdraw\n");
printf("5. Exit");
}
void open()
{
float avail_bal = 0;
char name[20];
int acc_num;
printf("Open new account(enter number 1-5)\n\n");
scanf("%d", &acc_num);
printf("Account number: %d\n");
printf("Available balance: %f\n");
}
void list()
{
}
void deposit()
{
float add;
int acc_num;
printf("Which count do you want to deposit money in?");
scanf(" %d", &acc_num);
printf("Amount to deposit: ");
scanf("%f", &add);
while()
{
}
}
void withdraw()
{
int acc_num;
float withdraw;
printf("Account to withdraw from: ");
scanf("%d", &acc_num);
printf("Amount to withdraw from account: ")
scanf("%f", &withdraw);
while()
{
printf("Current balance for account %d: %f ");
break;
} acc_num++
}
The problem with scanf was interesting. Here is an example for how to do without (although you shouldn't) such that you can play with your code easier.
#include <stdio.h>
#include <stdlib.h>
// only 5 accounts possible
int accounts[5];
// each its balance
float avail_bal[5];
void options();
// open(P) is a standard Posix function
void bopen();
void list();
void deposit();
void withdraw();
// exit(3) is a standard C function
void pexit();
int main(void)
{
char option;
while (1) {
printf("****Banking System WELCOME****\n");
printf("Enter 1-5 of the following options: \n");
options();
option = getc(stdin);
// swallow the '\n'
getc(stdin);
switch (option) {
case '1':
bopen();
break;
case '2':
list();
break;
case '3':
deposit();
break;
case '4':
withdraw();
break;
case '5':
pexit();
default:
pexit();
}
}
return 0;
}
void options()
{
puts("1. Open Account");
puts("2. List Accounts");
puts("3. Deposit");
puts("4. Withdraw");
puts("5. Exit");
}
void bopen()
{
int acc_num;
char c;
puts("Open new account(enter number 1-5)");
c = getc(stdin);
getc(stdin);
// assuming ASCII here where the digits 0-9 start at place 48 in the table
acc_num = (int) c - 48;
if (acc_num < 1 || acc_num > 5) {
puts("Account number must be between one and five inclusive");
return;
}
if (accounts[acc_num] != 0) {
printf("Account number %d is already taken\n", acc_num);
return;
}
// mark account as taken
accounts[acc_num] = 1;
// spend a fiver for the new client for being a new client
avail_bal[acc_num] = 5.0;
printf("Account number: %d\n", acc_num);
printf("Available balance: %f\n", avail_bal[acc_num]);
}
void list()
{
int i;
for (i = 0; i < 5; i++) {
if (accounts[i] != 0) {
printf("Account 000%d: %f\n", i, avail_bal[i]);
}
}
}
void deposit()
{
float add;
int acc_num;
char c;
char s[100];
puts("Which account do you want to deposit money in?");
c = getc(stdin);
getc(stdin);
acc_num = (int) c - 48;
printf("Amount to deposit: ");
// to get a number without scanf() we have to read the input as a string
// (fgets() adds a '\0' at the end, so keep a seat free for it)
fgets(s, 99, stdin);
// and convert it to a double (atof() only for brevity, use strtod() instead)
add = atof(s);
avail_bal[acc_num] += add;
printf("Amount deposited %f\n", add);
}
void withdraw()
{
int acc_num;
float withdraw;
char c;
char s[100];
// all checks ommitted!
puts("Account to withdraw from: ");
c = getc(stdin);
getc(stdin);
acc_num = (int) c - 48;
puts("Amount to withdraw from account: ");
fgets(s, 99, stdin);
withdraw = atof(s);
avail_bal[acc_num] -= withdraw;
printf("Current balance for account %d: %f\n", acc_num, avail_bal[acc_num]);
}
void pexit()
{
// place logic to save data here or use a function triggered by atexit() for that task
puts("Imagine all of your data would have been put in a safe place!");
exit(EXIT_SUCCESS);
}
Just replace the constructs with scanf before you pass your work for grading.
If you're using integer values as options why you are using character's
#include <stdio.h>
char name[20];
float avail_bal;
void options();
void open();
void list();
void deposit();
void withdraw();
void exit();
int main(void)
{
int option;
printf("****Banking System WELCOME****\n");
void options();
printf("Enter 1-5 of the following options: \n");
scanf("%d",&option);
switch(option)
{
case 1: open();
break;
case 2: list();
break;
case 3: deposit();
break;
case 4: withdraw();
break;
case 5: return 0;
default: exit();
break;
}
return 0;
}
void options()
{
printf("1. Open Account\n");
printf("2. List Accounts\n");
printf("3. Deposit\n");
printf("4. Withdraw\n");
printf("5. Exit");
}
void open()
{
float avail_bal = 0;
char name[20];
int acc_num;
printf("Open new account(enter number 1-5)\n\n");
scanf("%d", &acc_num);
printf("Account number: %d\n");
printf("Available balance: %f\n");
}
void list()
{
}
void deposit()
{
float add;
int acc_num;
printf("Which count do you want to deposit money in?");
scanf(" %d", &acc_num);
printf("Amount to deposit: ");
scanf("%f", &add);
while()
{
}
}
void withdraw()
{
int acc_num;
float withdraw;
printf("Account to withdraw from: ");
scanf("%d", &acc_num);
printf("Amount to withdraw from account: ")
scanf("%f", &withdraw);
while()
{
printf("Current balance for account %d: %f ");
break;
} acc_num++
}

Resources