C程序小问题

来源:百度知道 编辑:UC知道 时间:2024/06/29 21:04:45
printf("please enter an integer:");
while(scanf("%d",&n)!=1){
while(getchar()!='\n') ;printf("input incorrect.an integer again.");}这是中间一段程序,是为了防止使用者输入错误的数据。我试了试,的确是有这样的功能,但想问以下其中的while(getchar()!='\n') ;有什么作用?
我把while(getchar()!='\n')删除后为什么一旦输入错误就无限循环printf("input incorrect.an integer

while(scanf("%d",&n)!=1)--》如果输入格式不正确,如输入字符‘a’,则执行循环体。while(getchar()!='\n') --》读掉刚输入的所有废字符,如果删除此行,第一个while仍然scanf那个'a',还是格式不正确,继续死循环

"\n" 是回车符,也是一个字符串结束符,在这里是输入回车符结束内循环,你把while(getchar()!='\n')删除后是不是没删;printf("input incorrect.an integer again.");}那就成了while(scanf("%d",&n)!=1){;printf("input incorrect.an integer again.");}意思是只要输入的不是1那么就是一直执行循环输出input incorrect.an integer again

while(getchar()!='\n')的意思如果输入的不是回车键就执行下一条命令。“getchar()”是输入函数,“!=”是不等号,“'\n'”在这里意为回车。while()形成了无限循环

while(getchar()!='\n');
指的是当你输入回车符时,就结束循环,如果你去掉这一行
那么当你输入错误数据时,while(scanf("%d",&n)!=1) 条件成立
所以进入循环执行 printf("...");语句

这个表示只要你输入的不是换行符就可以循环下去啊

while(getchar()!='\n') ;printf("input incorrect.an integer again.");
是外层循环的循环体
while(getchar()!='\n')删除后
内层循环就只剩printf("input incor