getchar() not working in c

11.9k views Asked by At

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"

7

There are 7 answers

3
Filipe Gonçalves On BEST ANSWER

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.

1
Sourav Ghosh On

I think, in your code, the problem is with the leftover \n from

 scanf("%d",&x);

You can change that scanning statement to

scanf("%d%*c",&x);    

to eat up the newline. Then the next getchar() will wait for the user input, as expected.

That said, the return type of getchar() is int. You can check the man page for details. So, the returned value may not fit into a char always. Suggest changing ch to int from char.

Finally, the recommended signature of main() is int main(void).

3
Gaurav Sehgal On

When the user inputs x and presses enter,the new line character is left in the input stream after scanf() operation.Then when try you to read a char using getchar() it reads the same new line character.In short ch gets the value of newline character.You can use a loop to ignore newline character.

ch=getchar();
while(ch=='\n')
ch=getchar();
0
calvesmit On

Replacing ch = getchar(); with scanf(" %c", &ch); worked just fine for me!

But using fflush(stdin) after scanf didn't work.

0
Nikolas Manes On

When you using scanf getchar etc. everything you entered stored as a string (char sequence) in stdin (standard input), then the program uses what is needed and leaves the remains in stdin.

For example: 456 is {'4','5','6','\0'}, 4tf is {'4','t','f','\0'} with scanf("%d",&x); you ask the program to read an integer in the first case will read 456 and leave {'\0'} in stdin and in the second will read 4 and leave {''t','f',\0'}.

After the scanf you should use the fflush(stdin) in order to clear the input stream.

0
JorUge Ferrari On

My suggestion for you is to define a Macro like:

#define __GETCHAR__ if (getchar()=='\n') getchar();

Then you can use it like:

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

I agree that it is not the best option, but it is a little bit more elegant.

0
Shamim Ahmmed On

Add one more line ch = getchar(); between scanf("%d",&x); and ch = getchar(); then your code work correctly.
Because when you take input from user, in this time you press a new line \n after the integer value then the variable ch store this new line by this line of code ch = getchar(); and that's why you program crash because condition can not work correctly.
Because we know that a new line \n is also a char that's why you code crash.
So, for skip this new line \n add one more time ch = getchar();

like,

ch = getchar();  // this line of code skip your new line when you press enter key after taking input.
ch = getchar();  // this line store your char input

or

scanf("%d",&x);
ch = getchar();  // this line of code skip your new line when you press enter key after taking input.

pieces of code work correctly.