请教这个循环如何退不出
请问这个循环怎么退不出?
main()
{
int ret,n;
while(1)
{
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
if(ret==0)
{
printf("Your input is illegal!\n");
continue;
}
break;
}
}
当输入人不是数字时,这个循环怎么退不出,屏幕上老提示:
Please input the item of this Polynomail:
Your input is illegal!
------解决方案--------------------
ret=scanf("%d",&n);
这里要求输入数字,你不输入数字就出错了呗
------解决方案--------------------
fflush(stdin);
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
------解决方案--------------------
2楼 正确。
------解决方案--------------------
main()
{
int ret,n;
while(1)
{
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
if(ret==0)
{
printf("Your input is illegal!\n");
break; //是非数字字符就退出
}
continue; //是数字继续读取
}
}
------解决方案--------------------
2楼正确, 原因是预期要读入数字,如果输入的是非数字,则scanf会一直读取, 直到读到数字为止。可以在读取之前flush下。
------解决方案--------------------
ret=scanf("%d",&n);
当你输入非数字时返回值是0,所以循环了,
------解决方案--------------------
4楼能不能解释一下为什么该程序能实现是字符就停止呢?我分析并调试了好久,还是不怎么明白,谢谢
------解决方案--------------------
main()
{
int ret,n;
while(1)
{
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
if(ret==0)
{
printf("Your input is illegal!\n");
continue;
}
break;
}
}
当输入人不是数字时,这个循环怎么退不出,屏幕上老提示:
Please input the item of this Polynomail:
Your input is illegal!
------解决方案--------------------
ret=scanf("%d",&n);
这里要求输入数字,你不输入数字就出错了呗
------解决方案--------------------
fflush(stdin);
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
------解决方案--------------------
2楼 正确。
------解决方案--------------------
main()
{
int ret,n;
while(1)
{
printf("Please input the item of this Polynomail:\n");
ret=scanf("%d",&n);
if(ret==0)
{
printf("Your input is illegal!\n");
break; //是非数字字符就退出
}
continue; //是数字继续读取
}
}
------解决方案--------------------
2楼正确, 原因是预期要读入数字,如果输入的是非数字,则scanf会一直读取, 直到读到数字为止。可以在读取之前flush下。
------解决方案--------------------
ret=scanf("%d",&n);
当你输入非数字时返回值是0,所以循环了,
------解决方案--------------------
4楼能不能解释一下为什么该程序能实现是字符就停止呢?我分析并调试了好久,还是不怎么明白,谢谢
------解决方案--------------------
- C/C++ code
void main() { int ret,n; while(1) { printf("Please input the item of this Polynomail:\n"); ret=scanf("%d",&n); fflush(stdin);//加上这个,情况缓冲 if(ret==0) { printf("Your input is illegal!\n"); continue; } break; } }