I want to take input of integer and want to check that input is only one integer. So I have implemented some logic. But it's in infinite loop.
逻辑是:如果scanf返回1表示匹配,否则返回非整数,并且该数字应大于5,因此我也添加了该检查。
#include <stdio.h>
int main()
{
//Variable Declarations
int a[1000],n,i,j,int_check=0;
//Input for number of terms and it should be at least 5
printf("Enter the number of terms for the array input:");
int_check=scanf("%d",&n);
printf("\nscanf=%d and n=%d\n",int_check,n);
//Input Validity checking. If scanf returns 1 that means it's a match with the input. Number of terms should be greater than 5.
while(int_check!=1 || n<5)
{
printf("Enter the valid number of terms for the array inout. It should be an integer and greater than 5:");
int_check=scanf("%d",&n);
}
return 0;
}
它应该提供一个输入屏幕。帮助我确定此逻辑中的错误。
答案 0 :(得分:3)
如果您没有为scanf("%d",...);
输入有效的整数,则会删除 not 无效的输入,因此您将在下一个scanf("%d",...);
中得到它,因此(int_check!=1 || n<5)
将永远不要虚假
您需要自己清除无效输入,警告不要使用fflush(stdin);
,因为这仅适用于文件
请注意查看需要刷新的消息,例如,替换
printf("Enter the valid number of terms for the array inout. It should be an integer and greater than 5:");
作者
printf("Enter the valid number of terms for the array inout. It should be an integer and greater than 5:\n");
或在 printf 之后使用fflush(stdout);
,是您希望保持一致吗