Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This is a standard bank account program. Allowing for deposit,withdrawal,and viewing funds. I am having trouble getting the program to enter the functions inside my switch statement which is based on their choice. Here is the output of this code.
CodeOutput. I am not asking anyone to code for me, if you could maybe just point to where I went wrong.
#include <stdio.h>
float getDeposit(float currentBalance);
float getWithdrawal(float currentBalance);
float displayBalance(float currentBalance);
char displayMenu();
int main()
{
float currentBalance=200,newBalanceDep,newBalanceWith;
char choice;
choice = displayMenu();
switch (choice)
{
case 'D': case 'd':
newBalanceDep=getDeposit(currentBalance);
break;
case 'W': case 'w':
newBalanceWith=getWithdrawal(currentBalance);
break;
case 'B': case 'b':
displayBalance(currentBalance);
break;
case 'Q': case 'q':
printf("Thank you!");
break;
default:
printf("Invalid choice.");
break;
}
return 0;
}
char displayMenu()
{
char choice;
printf("Welcome to HFC Credit Union! \n");
printf("Please select from the following menu: \n");
printf("D: Make a deposit \n");
printf("W: Make a withdrawal \n");
printf("B: Check your account balance \n");
printf("Q: To quit \n");
scanf("\n%c",choice);
return choice;
}
float getDeposit(float currentBalance)
{
float depositAmount;
float newBalanceDep;
printf("Enter amount you would like to deposit: /n");
scanf("%f",&depositAmount);
if(depositAmount>0)
{
newBalanceDep=depositAmount+currentBalance;
}
return newBalanceDep;
}
float getWithdrawal(float currentBalance)
{
float withdrawalAmount;
float newBalanceWith;
printf("Enter amount you would like to withdrawal: /n");
scanf("%f",&withdrawalAmount);
if(withdrawalAmount>currentBalance)
{
printf("Insufficient Funds. Try again.");
printf("Enter amount you would like to withdrawal: /n");
scanf("%f",&withdrawalAmount);
}
else if(withdrawalAmount<=currentBalance)
{
newBalanceWith=withdrawalAmount+currentBalance;
}
return newBalanceWith;
}
float displayBalance(float currentBalance)
{
printf("Your current balance is %.2f",currentBalance);
}
You need to pass &choice to scanf, not choice.
char choice; /*...*/; scanf("\n%c",choice); // --->
// v---- add
char choice; /*...*/; scanf("\n%c",&choice);`
Passing choice is undefined behavior.
A good compiler should be giving you a warning.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new to programming. and I wanted to see how I could enhance the efficiency of this program, in terms of conciseness and security.
Also, how can I ensure that the user will not break the program by typing a character or a special symbol when I have asked for a number?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <math.h>
int main()
{
//Declaring Variables
float num1, num2;
int op;
char ans;
//Getting the user to choose an option
Again:
printf("\n\t\tMENU FOR OPERATIONS:\n ");
printf("\t\t____________________\n\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Modulus\n");
printf("6. Power Function\n\n");
printf("Enter the MENU option: ");
scanf("%d", &op);
while ( op != 1 && op != 2 && op != 3 && op != 4 && op != 5 && op != 6)
{
printf("\nYou entered an invalid MENU option!\n");
printf("Kindly try again.\n\n");
printf("Enter the MENU option: ");
scanf("%d", &op);
}
//Getting the numbers from user
printf("Enter the first number: ");
scanf("%f", &num1);
printf("Enter the second number: ");
scanf("%f", &num2);
//Implementing a switch statement for processing the input
switch(op)
{
//Case for Addition function
case 1:
printf("Result = %.1f\n", num1 + num2 );
break;
//Case for Subtraction function
case 2:
printf("Result = %.1f\n", num1 - num2);
break;
//Case for Multiplication function
case 3:
printf("Result = %.1f\n", num1 * num2);
break;
//Case for Division function
case 4:
printf("Result = %.1f\n", num1 / num2 );
break;
//Case for Modulus function
case 5:
printf("Result: %d\n",(int)num1 % (int)num2);
break;
//Case for Power Function
case 6:
printf("Result: %.1f\n", pow(num1, num2));
break;
default:
printf("You entered an invalid operator!\n\n");
break;
}
//Asking the user if he wants to run the program again
printf("\nDo you want to continue (Y/N)? ");
ans = getche();
ans = toupper(ans);
//Implementing a while loop to get the user to enter a valid character
while((ans != 'Y' ) && (ans != 'N'))
{
printf("\n\nYou must type a Y or an N!\n");
printf("Do you want to continue (Y/N)? ");
ans = getche();
ans = toupper(ans);
}
//Implementing an if statement to ascertain whether the user wants to continue or quit
if( ans == 'Y')
{
system("cls");
goto Again; //links the program to the start in case of a YES
}
else
{
exit(1); //Successfully exits the program in case of a NO
}
}
Stop using scanf() as a user interface function. It is not designed to be used as such, and you can easily found plenty of reasons why. I personally like this. Use combination of fgets() and sscanf, if necessary.
Yes, in the ctypes.h, there are functions like isalpha and isdigit etc.
Additionally, do not use goto as a flow control element, ever, as it leads to hard to debug, hard to read, hard to follow through spaghetti code. If your program logic is implemented by goto, that almost always means you didn't think enough on it.
As a side note, by convention most C functions return 0 in case of success, and a non-zero value indicating some sort of error. Here, i,t is not much of a problem, but if you find yourself writing a library or such, you will annoy your users.
When I run this program, it ignores everything in the switch statement, and displays the default.
I am using Code::Blocks.
Please explain to me why this logic error is encountered and maybe it is an error in Code::Blocks and not from the code — should I try it on another IDE?
#include <stdio.h>
int main()
{
double a,b;
int choose,subtract,divide;
printf("My first Calculater in c\n");
printf("\n");
printf("Enter your two numbers\n");
scanf("%lf",&a);
scanf("%lf",&b);
printf("Please choose an operation\n");
printf("1.add two no.(s)\n");
printf("2.subtract two no.(s)\n");
printf("3.multiply two no.(s)\n");
printf("4.divide two no.(s)\n");
printf("please choose an operation ");
scanf("%lf", &choose);
switch(choose){
case 1:
printf("sum of a+b is : %lf\n",(a+b));
break;
case 2:
printf("1.a-b?\n");
printf("2.b-a?\n");
scanf("%d", &subtract);
switch(subtract)
{
case 1:
printf("\ndiff of a-b is : %lf",(a-b));
break;
case 2:
printf("\ndiff of b-a is : %lf",(b-a));
break;
}
case 3:
printf("\nproduct of a*b is : %lf",(a*b));
break;
case 4:
printf("\n1.divide a/b?,a!=0");
printf("\n2.divide b/a?,b!=0");
scanf("%d", ÷);
switch(divide)
{
case 1:
if(b==0)
printf("\ndivision by zero is undefined");
else
printf("\nquotient of a/b is : %lf",(a/b));
break;
case 2:
if(a==0)
printf("\ndivision by zero is undefined");
else
printf("\nquotient of b/a is : %lf",(b/a));
break;
}
default:
printf("please choose either 1,2,3 or 4 options\n");
}
}
You are reading in a double for choose
scanf("%lf", &choose);
Change to reading a decimal
scanf("%d", &choose);
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);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code executes itself without asking for char "choose" for further processing before the switch statement scanf("%c",&choose); switch(choose).
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose);
In your code if you are using any scanf before the above given code, then this behaviour is expected as the previous scanf reads the input leaving \n in the input buffer which is feeded as input to next scanf.
To overcome this issue please use fflush(stream) before scanf(...), this should solve the problem.
fflush(stdin);
or you can use getchar() function, this will alse solve your the issue.
Probably because you've already input something earlier, so that there are non-scanned characters left in the buffer which this "greedy" scanf() then scans without stopping.
You should check the return value of scanf() to learn if it succeeded or not.
And you should switch to using fgets() to read in a whole line, and then parse that. It's much safer and easier to predict, that way.
I've executed it without any problems (it gets the "choose" char):
#include <stdio.h>
int main(int argc, char *argv ) {
char choose;
float a,b,c;
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
return 0;
}
Probably its something you didn't read before...
I'm guessing that you are doing a similar "scanf("%c",&choose);" before, so the next read you will get the carriage return.
You could try to change the following lines:
scanf("%c",&choose);
for:
scanf("%c%*c",&choose);
...so you discard the \n
If this don't solve your issue, maybe you should provide more code :)
I am trying to compile a small bank program in C in visual studio 2012 express. It shows me this error "undeclared identifier" for almost all variables and this one too "syntax error: missing ';' before 'type'".Please tell me the correct syntax.Thank you.
#include<stdio.h>
#include<conio.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%c",option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
The Microsoft C compiler only supports a 25 year old version of the language. And one of the limitations is that all variables must be declared before any other statements. So move all your variable declarations to the top of the function.
The next error I can see is the use of scanf_s with the %c format string. You must pass a pointer to the variable, and pass the number of characters to read.
scanf_s("%c", &option, 1);
And likewise you need to pass an address for the read of balance.
You also need to change the switch statement so that it just contains cases. Move the bare instructions outside.
Your reading of option won't work. Because when you check for 1 you are checking for the character with ASCII code 1. Change option to be an int and read using %d.
Perhaps you are looking for something like this:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int deposit,withdraw,kbalance;
int option;
int decash,wicash;
int balance;
int wibal;
printf("Welcome to skybank\n");
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%d", &option);
printf("Enter your current Balance\n");
scanf_s("%d", &balance);
switch(option)
{
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d", &decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n", decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d", &wicash);
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n", wicash);
printf("Your balance is %d\n", wibal);
break;
case 3:
printf("Your balance is Rs.%d\n", balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Regarding the unidentified variables, try putting all declarations of variables at the top of the main block, something like:
int main()
{
int deposit, withdraw, kbalance, decash, wicash, wibal;
char option;
printf("Welcome to skybank\n");
Older variants of C frown upon mixing variable declarations with code. To my knowledge the C standard of Microsoft's C implementation is pre-C99 so perhaps this could be the issue.
A few other issues that you should look into:
scanf_s("%c",option); - option should be &option as you are taking a pointer to that variable.
Also here: case 1:
You want '1' (as in case '1') instead of plain 1 as it is a char, not an int you want.
Same for the other case checks.
With regards to the scanf_s problems, try compiling with warnings, it should have been pointed out by the compiler.
Finally, you might want to rid your code of the variables you're not using such as kbalance, withdraw and deposit.
do at the beginning of the block in the declaration of the variable for visual c.
E.g.
int main()
{
int deposit,withdraw,kbalance;
char option;
int decash,wicash
int balance;
int wibal;
...
try this code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf("%c",&option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Move this:
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
Before the switch statement.