`

C语言中对scanf输入非法字符的检查和处理

 
阅读更多

在C中scanf()函数返回成功读入的变量的个数。如果它没有读取任何项目(输入非法字符,例如:希望得到数字,而用户却输入的是字符),scanf()返回值为0.当检测到“文件结尾”是,会返回EOF(EOF是在文件stdio.h中定义的特殊值,一般,#define指令把EOF的值定义为-1).

利用scanf()以上的性质,可对输入值进行检验,代码如下:

 

 

#include<stdio.h>

int main(void)
{
	 int num;
	 int status;
	 printf("input the value of num:");
	 status = scanf("%d",&num);
         if(status ==0)
	 {
		 printf("enter error");
                 fflush(stdin);//清除输入缓冲区的错误数据 
	 }
	 else if(status == EOF)
	 {
            printf("Input failure occurs!\n"); 
	 }

	 else
             printf("\nnum = %d\n",num);
	 fflush(stdin);
	 getchar();
	 
	 return 0;
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics