本文介绍了C语言中的无限循环代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的程序中,我尝试输入1
至100
之间的数字,但是如果在a 'character'
或"string"
(如s或sova
) >语句将创建一个无限循环.所以我尝试做.....当我输入字符串或字符时,它向我显示一条消息,例如输入了错误的值.请再次输入",然后它将再次输入...
谢谢;
In the below program I try to input a number between 1
to 100
but if I enter a
'character'
or "string"
( like s or sova
) during the execution time of scanf()
statement it creates a infinite loop. so I try to do .... when I input a string or a character it shown me a message like "wrong value entered. enter again" and it will enter again...
Thanx;
#include<stdio.h>
int main()
{
int a;
scanf("%d",&a);
while(!(a>=1&&a<=100))
{
printf("wrong value entered. enter again\n");
scanf("%d",&a);
}
printf("you enter %d. Thanxz",a);
return 0;
}
推荐答案
- 您需要检查
scanf
的返回值 - 如果用户未输入整数,则需要使用输入.
scanf
函数将继续说不是整数,然后重试.因此,如果scanf
返回0,则需要对其进行处理
- You need to check the return value of
scanf
- If the user has not entered a integer, you need to eat the input. The
scanf
function will continually say not a integer, try again. So ifscanf
returns 0 you need to deal with it
这篇关于C语言中的无限循环代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!