Swtich case issue in C language [duplicate] - c

This question already has answers here:
program wont read at second scanf()
(2 answers)
Closed 2 years ago.
I am making a mini project i c with the help of nested switch statement in my code Error is in 15th line of the code,here %c is not working but %s is working,please help me to solve this query and tell me how to run this code with the use of %c here is my code:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,ch;
char choice;
clrscr();
printf("1.Calculator\n2.Convrter\n\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
**scanf("%c",&choice);**
switch(choice)
{
case 'A':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a+b;
printf("%d",c);
break;
case 'S':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a-b;
printf("%d",c);
break;
case 'M':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a*b;
printf("%d",c);
break;
case 'D':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a/b;
printf("%d",c);
break;
case 'P':printf("Provide the value of a : ");
scanf("%d",&a);
printf("Provide the value of b : ");
scanf("%d",&b);
printf("\n");c=a%b;
printf("%d",c);
break;
default:printf("Invalid Input");
}
break;
}
getch();
}

you just need to add getchar(); before
scanf()
because you will take \n as char choice
so one getchar will solve your problem
case 1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
getchar();
scanf("%c", &choice);
switch (choice)
%s will work because it takes more than one char.
or you can:
1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
printf("Enter your choice : ");
scanf(" %c", &choice); //add space before %c
switch (choice)
as H.S. said in comment.

The previous call to scanf():
scanf("%d",&ch);
in Line 10, leaves the newline character (\n) made by the push to Enter/Return inside stdin.
This newline character is read on the second scanf() call since the %c format/conversion specifier does not ignore leading white space and also read/consumes non-printable characters.
Just insert white space before the conversion specifier %c:
scanf(" %c",&choice);
to catch that newline character or any leading white space.

Related

I couldn't input the character value in c [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
MY CODE:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf("%c",&g2);
printf("\nEnter the grade of student 3: ");
scanf("%c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
OUTPUT:
Enter the grade of student 1: A
Enter the grade of student 2:
Enter the grade of student 3:
//I am getting a line break and couldn't enter the value of student 2 and the cursor moves to student 3!!
Try doing:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf(" %c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
Sorry, I'm new to this.
Just give a space before %c in scanf to get desired input. The below is your own code where I've added space in the second and third scanf statements.
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
And well, the reason? If you don't, then the next scanf statement assumes the new line you create by pressing "Enter" as a new character, which is \n. So we add a space in scanf to let the statement know that space is not considered an input.
It is often easier to always read an entire line, like this:
#include <stdio.h>
void ReadLine(char result[], int resultLen)
{
int ch, i;
i = 0;
ch = getchar();
while ((ch != '\n') && (ch != EOF)) {
if (i < resultLen - 1) {
result[i] = ch;
i++;
}
ch = getchar();
}
result[i] = '\0';
}
int main(void)
{
char g1[2], g2[2] ,g3[2];
printf("Enter the grade of student 1: ");
ReadLine(g1, sizeof g1);
printf("Enter the grade of student 2: ");
ReadLine(g2, sizeof g2);
printf("Enter the grade of student 3: ");
ReadLine(g3, sizeof g3);
printf("%s%s%s\n", g1, g2, g3);
return 0;
}
first Scanf will not read/flush the "\n" after reading the single char.
this character on input buffer will make the 2nd and 3rd scanf to get execute and fail without actually prompting the user.
There are multiple ways to handle this.
read complete line
use gets/fgets to rad complete inputline
then use scanf to read from buffer
eg:
fgets(buff, 255, stdin);
sscanf(buff, "%c", &value);
execute a char read after every scanf statement.
getch()
Put a preceeding " " in front of every "%c" used in scanf.
this will skip the special char.
"scanf(" %c", &value);"

How do I make it when the program finished executing and add an option if the user want to try again it executes the program again

I got this school project in which we'll have to code a some sort of a calculator using Dev C++ and it has to have an option in which the user chooses weather to try and calculate again with a different inputs or another key to exit the program.
My problem is, on the option to try again or exit the program, when i input the option to execute again it just automatically executes everything and doesn't give the option to input characters or anything.
Here is my code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<unistd.h>
int main(){
int a,b,choice;
using namespace std;
system("cls");
printf("\t===============================================================\n"
);
printf("\n\t\t\t\tFinals Project I\n\n");
printf("\t\t\t Program Status : Complete\n\n");
printf("\t===============================================================\n\
n");
printf("Loading libraries...");
sleep(3);
printf("\tSuccess\n");
printf("Binding program libs...");
sleep(2);
printf("\tSuccess\n");
printf("Executing program...");
sleep(2);
printf("\tSuccess\n\n");
printf("Program Started!\n\n");
do{
printf("Please select valid operation (+ - / *):\t");
char operation;
scanf("%c", &operation);
switch(operation){
case '+':
printf("\nEnter 1st number:\t");
scanf("%d",&a);
printf("\nEnter 2nd number:\t");
scanf("%d",&b);
printf("\nAnswer is %d",a+b);
break;
case '-':
printf("Enter 1st number:\n");
scanf("%d",&a);
printf("Enter 2nd number:\n");
scanf("%d",&b);
printf("Answer is %d",a-b);
break;
case '/':
printf("Enter 1st number:\n");
scanf("%d",&a);
printf("Enter 2nd number:\n");
scanf("%d",&b);
printf("Answer is %d",a/b);
break;
case '*':
printf("Enter 1st number:\n");
scanf("%d",&a);
printf("Enter 2nd number:\n");
scanf("%d",&b);
printf("Answer is %d",a*b);
break;
default : printf("Incorrect! Operation not Valid...\n"); break;
}
printf("\nDo you want to try again? :\n[1] YES\n[0] NO\t :\t>>");
scanf("%d",&choice);
}while(choice!=0);
printf("\n\nExiting Program...[Press any Key]");
getch();
}
/*
((operation=='+')||(operation=='-')||(operation=='/')||(operation=='*'))
*/
I got it to work. Turns out I had to put "Space" before the "%c" on first scanf syntax. Thanks everyone for your comments and I'm sorry I was not specific with the code example. I copy and pasted everything.

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.

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

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

Problem with scanf [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Simple C scanf does not work?
Why does scanf("%c", &letter); not working. the rest is working
#include <stdio.h>
main(){
int number;
float number1;
char letter;
char letter2 [5];
printf("Enter an int: ");
scanf("%d", &number);
printf("Enter a float: ");
scanf("%f", &number1);
printf("Enter a letter: ");
scanf("%c", &letter);
printf("Enter a string: ");
scanf("%s", letter2);
printf("INT = %d\n", number);
printf("FLOAT = %f\n", number1);
printf("LETTER = %c\n", letter);
printf("LETTER2= %s\n", letter2);
getch();
}
This is because the newline (return key) after feeding float is counted as a character.
This is not a bug but it is due to fact that "\n" is considered a character in C and if you have to ignore it, you need to do that manually.
The simplest solution for your case is to eat up the newline as follows:
scanf("%f", &number1);
getchar();
This Link will help.
scanf reads the whitespace that is left in the buffer from the previous line. To skip the whitespace, add a space to the scanf:
scanf(" %c", &letter);
The space means "skip whitespace" and the the %c means "read the following character.

Resources