【发布时间】:2018-06-10 21:12:37
【问题描述】:
我在 C 语言中遇到了一个问题。我发布了问题和我在下面编写的代码。在这里,我必须在一个数组中输入 10 个数字,然后我需要检查一个数字出现了多少次。但是为了验证我输入了一个数字而不是其他任何东西,我使用了“isdigit()”函数。但这没有用。谁能帮我解决一下。
/* (a) 十个数字从键盘输入到一个数组中。要搜索的号码是通过输入 用户的键盘。编写程序查找要搜索的数字是否存在于数组中,如果存在则显示 它出现在数组中的次数。 */
#include<stdio.h>
#include<ctype.h>
main()
{
int num[10];
int i, j, cnt=0;
char rept;
printf("Enter 10 numbers: \n\n");
for(i=0; i<=9; i++)
{
printf("Number %d = ", i+1);
scanf("%d", &num[i]);
fflush(stdin);
if ( !isdigit(num[i]) )
{
printf("OK\n");
}
else
{
printf("Invalid number. Enter again.\n");
i=i-1;
}
}
do
{
printf("\nEnter the number to be searched in array: ");
scanf(" %d", &j);
for (i=0 ; i<=24; i++)
{
if(num[i]==j)
cnt++;
}
if(cnt>0)
printf("\nNumber %d is present at %d places", j, cnt);
else
printf("\nNumber not present.");
printf("\n\nDo you want to search another number. Press Y to repeat. Any other key to exit");
fflush(stdin);
scanf("%c", &rept);
}while (rept=='y'||rept=='Y');
getch();
}
【问题讨论】:
-
谁或什么文字建议使用
fflush(stdin);? -
您是否阅读了
scanf()的文档?尤其是讨论其返回值的部分? -
另外请记住,
main()在 20 年前就已经过时了,并且在 2011 年被认定为非法。请使用int main(void)。
标签: c