Not asking for char "choose" Before switch statement [closed] - c

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 :)

Related

C Program, Array inside a case in continuous Switch Menu loop

My array inside case 4 in looping Switch Menu doesn't print/display the value of the last array when the user input goes beyond array[4].
I tried to take the case 4 out and make it a single program to check if it doesn't really work on its own but it works fine, but when I put it back into the Switch, same issue again. I thought that maybe the initialization part is the problem. Help
`
#include <stdio.h>
int main ()
{
char first[20],last[20];
float math,eng,sci,avg;
int a,b,c,d,diff,array[diff],e,i,input;
do{
printf("\nMAIN MENU\n");
printf("[1] Basic Input Output\n[2] Conditional Statement\n[3] Looping Construct\n[4] Array\n[5] About\n[6] Exit");
printf("\n\nChoose: ");
scanf("%d",&input);
printf("\n");
switch (input)
{
case 1:
printf("\nEnter your given name:");
scanf("%s",first);
printf("Enter your surname:");
scanf("%s",last);
printf("\nHello %s %s!\n",first,last);
break;
case 2:
printf("\nEnter your grade in Math:");
scanf("%f",&math);
printf("\nEnter your grade in Science:");
scanf("%f",&sci);
printf("\nEnter your grade in English:");
scanf("%f",&eng);
avg=(math+eng+sci)/3;
if(math>eng&&sci)
{
printf("\nHighest grade is in: Math");
}
if(eng>math&&sci)
{
printf("\nHighest grade is in: English");
}
if(sci>eng&&math)
{
printf("\nHighest grade is in: Science");
}
if(math==eng)
{
printf("\n--Math and English tied grades--");
}
if(math==sci)
{
printf("\n--Math and Science tied grades--");
}
if(eng==sci)
{
printf("\n--Science and English tied grades--");
}
printf("\nYour average in 3 subjects:%f\n",avg);
break;
case 3:
printf("Enter beginning number: ");
scanf("%d",&b);
printf("Enter ending number: ");
scanf("%d",&c);
printf("\nCounting from %d to %d\n",b,c);
while(b<=c)
{
printf("%d ",b);
b++;
}
printf("\n");
break;
case 4:
printf("Enter Starting Series of Numbers: ");
scanf("%d",&a);
printf("Enter Ending Series of Numbers: ");
scanf("%d",&d);
diff=(d-a);
array[diff]=d;
printf("Select Array Value to Display: 0 to %d: ",diff);
scanf("%d",&e);
for(i=0;i<=diff;i++)
{
array[i]=a;
if(i==e)
{
printf("%d\n",array[i]);
}
a++;
}
break;
case 5:
printf("Abouts\n");
break;
case 6:
printf("Thank you!");
break;
}
}while(input != 6);
return 0;
}
`
This should be a comment, but I donĀ“t have enough reputation yet.
As Gerhardh said, the problem is that you use diff before being initialized (which causes undefined behaviour)
As you said, if you move the initialization of array inside the case 4: after diff being set the program should work as intended. If you want to keep it before the switch, try using int* and malloc/free inside the case 4: (and add #include <stdlib.h>) Anyway, you should check diff as positive value before using it to set the size of array
About optimizing the code, you can skip the line array[diff]=d; because you are setting the same value inside the for loop. And you can remove the line a++; if you changes array[i]=a; -> array[i]=a+i;

How to make so that code will ask me what it want to do [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
How to do scanf for single char in C [duplicate]
(11 answers)
Scanf skips every other while loop in C
(10 answers)
Closed 4 months ago.
i created a code that converts the temperature into another form, like if you want to convert celcius to farenheit or kevlin and vice versa. But it isnt working as i thought.
code:-
#include <stdio.h>
int main()
{
float a, b;
char c, e;
printf("What you want to change\ntype c for celcius, f for farenheit or k for kelvin: ");
scanf("%c", &c);
switch (c)
{
case 'c':
printf("Now put the celcius value you want to convert: ");
scanf("%f", &a);
printf("Now in which you want to change\ntype f for farenheit or k for kelvin: ");
scanf("%c", &e);
switch (e)
{
case 'f':
printf("The farenheit value of %0.2f degree celcius: %0.2f\n", a, a*1.8+32);
break;
case 'k':
printf("The kelvin value of %0.2f degree celcius: %0.2f\n", a, a+273.15);
break;
default:
printf("You didnt put the correct operation");
break;
}
break;
case 'f':
printf("Now put the farenheit value you want to change into celcius: ");
scanf("%f", &a);
b = ((a-32)*5)/9;
printf("Now in which you want to change\ntype c for celcius or k for kelvin: ");
scanf("%c", &e);
switch (e) {
case 'c':
printf("The celcius value of %0.2f degree farenheit: %.2f\n", a, b);
break;
case 'k':
printf("The kelvin value of %0.2f degree farenheit: %0.2f\n", a, b+273.15);
break;
default:
printf("You didnt put the correct operation");
break;
}
break;
case 'k':
printf("Now put the kelvin value you want to change: ");
scanf("%f", &a);
if (a>=0) {
printf("Now in which you want to change\ntype c for celcius or f for farenheit: ");
scanf("%c", &e);
b=(a-273.15)*1.8+32;
switch (e) {
case 'c':
printf("The celcius value of %0.2f kelvin in celcius is: %0.2f\n", a, a-273.15);
break;
case 'f':
printf("The farenheit value of %0.2f kelvin in farenheit is: %0.2f\n", a, b);
break;
default:
printf("You didnt put the correct operation");
break;
}}
else {
printf("Kelvin cannot be less than zero");
}
break;
default:
printf("You didnt put the correct spell of what you want to change\n");
break;
}
return 0;
}
I was trying to make it so that it will ask the user in which you want to change but it didnt worked as i thought. It isnt asking for what you want to change and skips that scanf function.
The issue you're getting is that scanf leaves a newline character in the buffer after getting the float. Then the scanf for the character gets the newline and you're switch statement goes to the default statement. This is a major flaw of scanf and can be very confusing for new users of C. One potential solution to this is to clear the buffer using this:
while ((c = getchar()) != '\n' && c != EOF);
This uses getchar (which takes one character from the same buffer as scanf) and will loop until getchar gets a newline or gets to the end of the buffer. Then when you run scanf it will have an empty buffer an take input from the user.

C joining two functions [closed]

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.

Switch statement closing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am writing a switch statement that is supposed to act like a simple calculator, and when I select case 5 it's supposed to toggle between single and double precision. However when I select case 5, I get Calculator now works with double precision. and it exits the program. It was actually working before until I added case 6 which is supposed to be the one that exit's the program.
int opt;
float first, second, sum, difference, product, quotient;
double first_d, second_d, sum_d, difference_d, product_d, quotient_d;
char ch;
printf("This program implements a calculator. Options:\n");
printf(" 1 - addition\n 2 - subtraction\n 3 - multiplication\n 4 - division\n");
printf(" 5 - toggle precision\n 6 - exit program");
ch = getchar();
for(;;) {
printf("Please enter your option:");
scanf("%d", &opt);
switch (opt) {
case 1:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
sum = first + second;
printf("The sum is: %f\n", sum);
break;
case 2:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
difference = first - second;
printf("the difference is: %f\n", difference);
break;
case 3:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
product = first * second;
printf("The product is: %f\n", product);
break;
case 4:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
quotient = first/ (float)second;
printf("The quotient is: %f\n", quotient);
if(second == 0){
printf("Cannot divide by 0!\n");
}
break;
case 5:
if(ch != '1' && '2' && '3' && '4' && '6'){
printf("Calculator now works with double precision.\n");
switch (opt) {
case 1:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
sum_d = first_d + second_d;
printf("The sum is: %lf\n", sum_d);
break;
case 2:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
difference_d = first_d - second_d;
printf("the difference is: %lf\n", difference_d);
break;
case 3:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
product_d = first_d * second_d;
printf("The product is: %lf\n", product_d);
break;
case 4:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
quotient_d = first_d/ (double)second_d;
printf("The quotient is: %lf\n", quotient_d);
if(second_d == 0){
printf("Cannot divide by 0!\n");
} else {
printf("Calculator now works with single precision.\n");
}
break;
}
}
case 6:
return 0;
default:
printf(" 1 - addition\n 2 - subtraction\n 3 - multiplication\n 4 - division\n");
printf(" 5 - toggle precision\n 6 - exit program\n");
break;
}
}
}
As the comments on your original post have said, you simply forgot a break.
After your fifth case, a break would cause the code to leave the switch statement and continue looping input. Because you forgot this break, the code finished in the fifth case and continued into the sixth case. The sixth case then exits, which is what your output was originally.
Add a break statement at the end of the fifth case, and you should be all set to go.

Program Ends Before Enter The Inputs(switch case) [duplicate]

This question already has answers here:
How to do scanf for single char in C [duplicate]
(11 answers)
Closed 8 years ago.
I m new in c programing
I write a program. But when i run the program before i entered my choice program ends.
Here is the screenshot.
https://onedrive.live.com/download?resid=E63780628DD96583!3161&authkey=!APl3ReO7T4XIO_s&v=3&ithint=photo,jpg
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice: ");
scanf("%c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\The Subsraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
getch();
return 0;
}
Where Did I Do The Mistake???
Add a space before %c in the scanf will solve the issue.This happens because scanf does not consume the \n character after you enter the values of the first two integers.As the Enter key(\n) is also a character,it gets consumed by the scanf("%c",&ch); and thus,your default case gets executed.The space before the %c will discard all blanks and spaces.

Resources