cwhile-loopcharscanfgetchar

getchar() not working in c


getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working.

I am not able to figure out the root cause of the issue, can anyone please help me.

#include<stdio.h>
int main()
{
        int x, n=0, p=0,z=0,i=0;
        char ch;

        do
        {
                printf("\nEnter a number : ");
                scanf("%d",&x);

                if (x<0)
                        n++;
                else if (x>0)
                        p++;
                else
                        z++;

                printf("\nAny more number want to enter : Y , N ? ");
                ch = getchar();

                i++;

        }while(ch=='y'||ch=='Y');
        printf("\nTotal numbers entered : %d\n",i);
        printf("Total Negative Number : %d\n",n);
        printf("Total Positive number : %d\n",p);
        printf("Total Zero            : %d\n",z);
        return 0 ;
}

The code has been copied from the book of "Yashvant Kanetkar"


Solution

  • That's because scanf() left the trailing newline in input.

    I suggest replacing this:

    ch = getchar();
    

    With:

    scanf(" %c", &ch);
    

    Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than consuming a single char in the previous scanf() because it ignores any number of blanks.