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;
}
Related
Problem: Scholarship Endowment Fund Part 2 (fund2.c)
How do I return back to main menu and add a counter for the total number of donations and investment made, here's what i got?
Then, your program should allow the user the following options:
Make a donation
Make an investment
Print balance of fund
Quit
#include <stdio.h>
#include <stdlib.h>
//main functions
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
if (ans == 1) {
printf("How much would you like to donate?\n");
scanf("%d", &donation);
}
if (ans == 2) {
printf("How much would you like to invest?\n");
scanf("%d", &investment);
return main();
}
if (ans == 3) {
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
return main();
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
}
if (ans == 4) {
printf("Type 4 to quit\n");
}
else {
printf("Not a valid option.\n");
}
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
return main();
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
return main();
case 3:
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
return main();
case 4:
break;
}
return 0;
}
You should put in a loop the part that you want to be repeated, using a varaible to decide when to stop.
here is an example, also in the switch costruct you should usa a default option, maybe to warn the user that the option they inserted is not valid.
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
//loop until the user decide so
int exit = 0;
while(exit == 0){
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
break;
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
break;
case 3:
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
break;
case 4:
exit = 1;
break;
default:
printf("Incorrect option\n");
break;
}
}
return 0;
}
I created a C Program that will take all the order of the user then generate the grandtotal of the orders.
But when I will order another food, the program is closing automatically.
I don't know if this is about my getch or the breaks in my switch method. Sometimes, it will proceed to take another error but it automatically outputs "INVALID FOOD".
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void menu();
void foods();
void main();
char food;
int quantity;
float price;
float total;
float grandtotal;
int choice;
void main()
{
clrscr();
menu();
foods();
getch();
}
void menu(){
food = ' ';
quantity = 0;
price = 0;
total = 0;
choice = 0;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
scanf("%c", &food);
}
void foods(){
switch(food)
{
case 'B':
printf("You selected Burger!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 95.50;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'F':
printf("You selected French Fries!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 47.75;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'P':
printf("You selected French Pizza!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 105.00;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'S':
printf("You selected Sandwiches\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 75.50;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
main();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
default:
printf("INVALID FOOD!");
break;
}
}
I wish someone could help or guide me. Thanks in advance.
In you code you have duplicated multiple times:
...
if(choice == 1){
menu();
break;
} ...
...
So when you choose choice = 1 then menu() get's displayed, and then the code breaks out of foods(). I think you meant to do the foods section again:
...
if(choice == 1){
menu();
foods();
break;
} ...
...
Yet another problem in your code is the %c scanf modifier. It will not eat up leading whitespaces, so it will read a newline (inputted on the last scanf). Use a leading space " %c" to tell scanf to read up leading whitespaces and ignore the leading newline, in scanf(" %c", &food);
Indent your code.
Don't duplicate statements. The whole scanf(... &choice); if (choice == 1) ... else if (choice == 2) could be placed outside the while switch not beeing duplicated 4 times.
Nesting functions using recursive calls can make your stack run out. Better just use a while loop.
Try not to use global variables. They are misleading and lead to maintainable code.
A slightly modified version of you code with a bit of indententation, added a do ... while loop and removed global variables and code duplication, may look like this:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
char menu(void);
float foods(char food);
void main()
{
clrscr();
float grandtotal = 0;
int choice = 0;
do {
// print menu and choose the food
char food = menu();
// choose food quantity and get it's price
float total = foods(food);
// print the total price
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
// do you want to continue?
printf("\n Do you want to order more? [1] Yes [2] No:");
if (scanf("%d", &choice) != 1) {
perror("scanf error");
abort();
}
// continue until choice is equal to 1
} while (choice != 1);
}
char menu(void)
{
char food;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
if (scanf(" %c", &food) != 1) {
perror("scanf error");
abort();
}
return food;
}
float foods(char food){
float price = 0;
switch (food) {
case 'B':
printf("You selected Burger!\n");
price = 95.50;
break;
case 'F':
printf("You selected French Fries!\n");
price = 47.75;
break;
case 'P':
printf("You selected French Pizza!\n");
price = 105.00;
break;
case 'S':
printf("You selected Sandwiches\n");
price = 75.50;
break;
default:
fprintf(stderr, "INVALID FOOD!\n");
abort();
}
printf("Enter quantity:");
int quantity;
if (scanf("%d", &quantity) != 1) {
perror("scanf error");
abort();
}
return (float)price * (float)quantity;
}
When you call menu after user input is [1] yes. with menu() function show menu and after menu you should show call food() function.
HERE WHAT YOU WANT
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void menu();
void foods();
void main();
char food;
int quantity;
float price;
float total;
float grandtotal;
int choice;
void main()
{
clrscr();
do {
menu();
foods();
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
getchar(); // <== remove newline
grandtotal = grandtotal + total;
} while (choice == 1);
printf("\n Total Price is: %0.2f", grandtotal);
getch();
}
void menu() {
food = ' ';
quantity = 0;
price = 0;
total = 0;
choice = 0;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
scanf("%c", &food);
}
void foods() {
switch (food)
{
case 'B':
printf("You selected Burger!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 95.50;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
//getchar(); // <== remove newline
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'F':
printf("You selected French Fries!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 47.75;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'P':
printf("You selected French Pizza!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 105.00;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'S':
printf("You selected Sandwiches\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 75.50;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// main();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
default:
printf("INVALID FOOD!");
break;
}
}
I'm getting an error which I am not able to resolve. I've gone through my code thoroughly with no success. What am I doing wrong? See code below.
Compiler error:
In function 'main':
ou1.c:49:1: error: expected 'while' before 'printf'
printf("End of program!\n");
^
My code:
#include <stdio.h>
int main(void){
int choice;
float price, sum, SUMusd;
float rate =1;
printf("Your shopping assistant");
do{
printf("1. Set exchange rate in usd (currency rate:%f)\n", rate);
printf("2. Read prices in the foreign currency\n");
printf("3. End\n");
printf("\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Give exchange rate: \n");
scanf("%f", &rate);
break;
case 2:
do{
printf("Give price(finsh with < 0)\n");
scanf("%f", &price);
sum =+ price;
}while(price <= 0);
SUMusd = sum*rate;
printf("Sum in foreign currency: %f", sum);
printf("Sum in USD:%f", SUMusd);
break;
default:
printf("Invalid choice\n");
break;
}while(choice != 3);
}
printf("End of program!\n");
return 0;
}
The curly braces of the switch statement need to be closed before the while loop termination.
printf("Invalid choice\n");
break;
}
}while(choice != 3);
printf("End of program!\n");
Corrected full code sample
#include <stdio.h>
int main(void){
int choice;
float price, sum, SUMusd;
float rate =1;
printf("Your shopping assistant");
do{
printf("1. Set exchange rate in usd (currency rate:%f)\n", rate);
printf("2. Read prices in the foreign currency\n");
printf("3. End\n");
printf("\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Give exchange rate: \n");
scanf("%f", &rate);
break;
case 2:
do{
printf("Give price(finsh with < 0)\n");
scanf("%f", &price);
sum =+ price;
}while(price <= 0);
SUMusd = sum*rate;
printf("Sum in foreign currency: %f", sum);
printf("Sum in USD:%f", SUMusd);
break;
default:
printf("Invalid choice\n");
break;
}
}while(choice != 3);
printf("End of program!\n");
return 0;
}
#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.
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++
}