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"
Replacing
ch = getchar();
withscanf(" %c", &ch);
worked just fine for me!But using
fflush(stdin)
afterscanf
didn't work.I think, in your code, the problem is with the leftover
\n
fromYou can change that scanning statement to
to eat up the
newline
. Then the nextgetchar()
will wait for the user input, as expected.That said, the return type of
getchar()
isint
. You can check the man page for details. So, the returned value may not fit into achar
always. Suggest changingch
toint
fromchar
.Finally, the recommended signature of
main()
isint main(void)
.When the user inputs
x
and presses enter,the new line character is left in the input stream afterscanf()
operation.Then when try you to read a char usinggetchar()
it reads the same new line character.In shortch
gets the value of newline character.You can use a loop to ignore newline character.That's because
scanf()
left the trailing newline in input.I suggest replacing this:
With:
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 previousscanf()
because it ignores any number of blanks.When you using
scanf
getchar
etc. everything you entered stored as a string (char sequence) instdin
(standard input), then the program uses what is needed and leaves the remains instdin
.For example: 456 is
{'4','5','6','\0'}
, 4tf is{'4','t','f','\0'}
withscanf("%d",&x);
you ask the program to read an integer in the first case will read 456 and leave{'\0'}
instdin
and in the second will read 4 and leave{''t','f',\0'}
.After the
scanf
you should use thefflush(stdin)
in order to clear the input stream.