[英]Infinite loop code in C
在下面的程序中,我试着输入之间的数字1
到100
,但如果我输入a
'character'
或"string"
(如S或sova
中的执行时间) scanf()
声明它创建了一个无限循环。 所以我试着做....当我输入一个字符串或一个字符时,它向我显示一条消息,例如“输入了错误的值。再次输入”,它将再次输入...
感谢名单;
#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,则需要处理它 当您使用scanf时,您正在使用缓冲输入,这意味着当您输入值“123”并按ENTER时,“123”加上结束字符(ENTER)将全部添加到缓冲区。 然后scanf
删除123,因为%d
指定应该读取整数,但如果用户输入的内容像字符串一样无效,则缓冲区将不会被清空。
从键盘读取输入的更好方法是使用fgets(),您可以在其中指定要读取的最大长度。 输入后,您可以使用sscanf()从中检索数值。 ENTER直到那时不会激怒你的输入。
char buffer[128];
fgets( buffer, 128, stdin );
sscanf( buffer, "%d", &a );
还要始终根据经验检查函数的返回值,以便在函数失败时执行适当的操作。
尝试这个。
#include <stdio.h>
#define FLUSH while (getchar() != '\n') // macro to eat invalid input
int main (void) {
int a = 0;
printf ("Enter an integer: ");
scanf("%d", &a);
while (a < 1 || a > 100) {
FLUSH;
printf("Invalid input. Please try again: ");
scanf("%d",&a);
}
printf("You entered %d.\nThanks!\n", a);
return 0;
}
您的代码显示了需要更改的几种编码习惯:
main()
的参数列表中包含(void)
main()
。 while(!(a>=1&&a<=100))
是不必要的丑陋和难以阅读。 (! (a>=1 && a<=100))
当它意味着与(a < 1 || a > 100)
同时,后者更容易阅读? 如果scanf的返回值不等于您希望用户输入的项目数,请读取输入缓冲区的所有字符,直到有'\\ n'为止。 但是,不是将一个完整的循环一遍又一遍地复制到代码中用户应该输入内容的位置,而是可以将循环包装在这样的函数中:
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
void input(const char *format,...)
{
va_list ap;
int r;
/* number of items [to read] */
int noi=0;
for(r=0;r<strlen(format)-1;r++)
{
if(format[r]=='%')
{
if(format[r+1]!='%')
noi++;
else
r++;
}
}
do
{
va_start(ap,format);
r=vscanf(format,ap);
va_end(ap);
if(r!=noi)
{
switch(r)
{
case EOF:
case 0:
printf("All wrong, try again!\n");
break;
default:
printf("Unexpected value after item no %d!\n",r);
}
while(getc(stdin)!='\n');
}
else
break;
} while(1);
}
希望有所帮助,
一月
为什么你使用循环,你的逻辑似乎必须有一个if --- else条件
while (1)
{
if (a>=1&&a<=100)
{
printf("wrong value entered. enter again\n");
scanf("%d",&a);
}
else
{
printf("you enter %d. Thanxz",a);
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.