耳环什么品牌好:C问题请教~~~

来源:百度文库 编辑:神马品牌网 时间:2024/05/14 02:20:21
一段程序:
#define N 5
main()
{
int a[N],i;
printf("\n");
for(i=1;i<N;i++)
{
printf("input %d:",i);
fflush(stdin);
scanf("%d",&a[i]);
}
//如果我输入的值为12 32 hr,怎样控制我不输入非数字的数据?
}
数组里的数据我在后面要用来运算的

没有办法控制你,你个大活人,怎么控制呢。只能说,你输入进来以后,程序进行检查。这里就不能使用 scanf(),而要用 gets()。不管用户输入什么,都作为字符串读入,检查了字符串是否合法以后,再转换为数字。

可以检查scanf的返回值。
比如scanf("%d %d",&x,&y);如果你输入两个整数,则scanf返回2;如果你只输入了一个整数,则返回1;如果输入的两个都不是整数,则返回0。

你可以看一看scanf函数的msdn帮助:这对你以后的解决问题非常的重要,每

一个程序员都会有一个msdn帮助,包括微软的专家。

这是函数的原型:

int scanf( const char *format [,argument]... );
int wscanf( const wchar_t *format [,argument]... );
Parameters

format
Format control string
argument
Optional arguments
Libraries

All versions of the C run-time libraries.

Return Values

Both scanf and wscanf return the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.

你可以看到他的返回值是int,表示按照输入格式要求的输入,如果你实际的

输入和要求有差别,那么返回值就会是0。