C语言 如何正确循环输入一个整数,浮点和字符串报错

来源:互联网 发布:全网营销推广软件 编辑:程序博客网 时间:2024/04/27 18:54

1.如何保证循环输入——一定要flush(stdin)清除缓冲区

2. 如何保证输入不是字符串—  ret=scanf("%f",&dN)),输入整数或者浮点数就会返回1!(注意,很多人觉得)     

3.如何保证输入不是浮点数,而是整数——强制转化N=(int)(dN);用(N+0.0)!=dN判断之

代码如下

              int N=-2;

              float dN=0.0;

fflush(stdin);/*刷新缓冲区*/
int ret=0;
while ((ret=scanf("%f",&dN))!=1)/
{
printf("\ninput is wrong\n");
fflush(stdin);

}

N=(int)(dN);

/*判断N为合法整数*/
if(N<3||N>100||(N+0.0)!=dN)
{

printf("\ninput is wrong\n");
continue;

}

Note:有人感觉如下更简单,其实是错误的,因为此时,输入是12.5,会当成输入12的

                int N=-2;

fflush(stdin);/*刷新缓冲区*/
int ret=0;
while ((ret=scanf("%d",&N))!=1)/
{
printf("\ninput is wrong\n");
fflush(stdin);

}
/*判断N为合法整数*/
if(N<3||N>100)
{

printf("\ninput is wrong\n");
continue;

}