1

I am working on a mini project in C.I am making a Calculator & Converter in C using nested switch case.And here "%c" is not working for "char choice",instead of that it is working with "%s" although I did'nt declare any "string" in the program. Here is the code of the project:-

#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();
}
  • Let me guess: You end the numeric input (for the `scanf("%d",&ch)`) with the `Enter` key, right? That adds a newline in the input buffer, Which is read by your character reading (the `scanf("%c",&choice)`). You need to prefix the `%c` format specifier with a space to tell `scanf` to skip all leading white-space, like the newline (it's only needed for the `%c` and `%[` formats). – Some programmer dude Mar 09 '20 at 09:06
  • Most format specifiers automatically filter leading whitespace (such as a newline) from the input, however `%c` and `%[]` and `%n` do not. – Weather Vane Mar 09 '20 at 09:09
  • What should I do to run this code?? – Keval Vora Mar 09 '20 at 10:48

0 Answers0