Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switch always runs default inside a while loop

#include<stdio.h>

int main()
{
    char a;

    do {
    printf("\n enter letter a,b or c: ");
    scanf("%c", &a);

    switch (a)
    {
    case  'a' :
        printf("\n one \n");
        break;
    case  'b' :
        printf("\n two \n");
        break;
    case  'c' :
        printf("\n three \n");
        break;
    default:
        printf("\n invalid input \n");
        break;
    }
    }while(a != 'd');
}

this code always runs default even there is a break;

but if u replace %c to %s, it works normally, i just want to understand why using %c does that or is there any other way to make it run perfectly with using %c

also using a=getch() works but i want to display the input without using printf to display it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When using scanf, you need to press enter key after the letter a/b/c to send the input. %c interprets your input as two characters. One for actual letter you inputted and the second for the enter key. It is this enter key character that passes through ‘default’ case. When you use getch(), everything works fine because you don’t press the enter key

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading