Search code examples
cdo-whilegetchar

Why taking input with getchar() falls in infinite loop?


Code:

#include <stdio.h>

int main()
{
    char ch;
    do
    {
        printf("Enter first letter?  ");
        ch=getchar();
        //scanf("%c", &ch);
    }
    while(ch!='A' || ch!='S' || ch!='M' || ch!='D');
    printf("\n terminate here");

    return 0;
}

Output:

Runtime error   time: 0 memory: 2160 signal:25
Enter first letter?  Enter first letter?  Enter first letter?  Enter     first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter?  Enter first letter? 

I tried all possible ways but no luck. The scanf() is also not working. What is wrong with the code?


Solution

  • Suppose, you gave A as input, then the first condition did not satisfied, but the other conditions are satisfied. Same is true for S, M and O.

    It seemed to me that you are trying to stop your while loop when you get one of the above four letters. It can be done in various way like ch!='A' && ch!='S' &&ch!='M' && ch!='D' or !(ch!='A' || ch!='S' ||ch!='M' ||ch!='D').

    I used the second one in the code as it needs little change in your code.

    #include <stdio.h>
    
    int main()
    {
        char ch;
        do
        {
            printf("Enter first letter?  ");
            ch=getchar();
            getchar(); // extra getchar
    //scanf("%c", &ch);
        }
        while(!(ch!='A' || ch!='S' ||ch!='M' ||ch!='D'));
        printf("\n terminate here");
    
        return 0;
    }
    

    N.B.

    You have to give an extra getchar() because after inputting a letter you are giving enter button. The second getchar() is for taking this new line(\n) and ignoring. If you assign the input from second getchar() in a variable and print the ASCII character, you would find the same value of \n.