getchar()在c中不起作用
getchar()在以下程序中不起作用,任何人都可以帮助我解决此问题。我尝试用scanf()函数代替getchar(),但是它也不起作用。
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 ;
}
该代码已从 Yashvant Kanetkar书中复制
The code has been copied from the book of "Yashvant Kanetkar"
这是因为 scanf()
在输入中留下了结尾的换行符。
That's because scanf()
left the trailing newline in input.
我建议替换为:
ch = getchar();
使用:
scanf(" %c", &ch);
请注意格式字符串中的前导空格。需要强制 scanf()
忽略每个空格字符,直到读取非空格为止。通常,这比在以前的 scanf()
中使用单个字符更健壮,因为它忽略了任何个空格。
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.