//如果错误的话,为什么代码会无限地开始打印重试 在终端
中输入一个字符串代替int i#include<stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[])
{
int i,j=0;
while(1)
{
scanf("%d",&i);
if(i==10)
{
printf("you got the max! YOU WON\n");
break;
}
else
{
printf("%s\n","retry" );
}
}
return 0;
}
答案 0 :(得分:3)
尝试在输入错误时使用(刷新):
else {
while ((j = fgetc(stdin)) != '\n' && j != EOF);
printf("%s\n", "retry");
}
使用fgets
的替代方案(最好是因为它占用整行)和strtol
:
#include <stdio.h> /* fgets, printf */
#include <stdlib.h> /* strtol */
#include <string.h> /* strchr */
int main(void) /* No args */
{
char buf[128], *p;
int i;
while (fgets(buf, sizeof(buf), stdin)) {
if ((p = strchr(buf, '\n')) != NULL) {
*p = '\0'; /* remove newline */
}
i = (int)strtol(buf, &p, 10); /* Base 10 */
if (*p != '\0' || i != 10) {
printf("retry\n");
} else {
printf("you got the max! YOU WON\n");
break;
}
}
return 0;
}
答案 1 :(得分:2)
由于您输入了错误的类型而导致读取失败,i
将具有垃圾值。
将初始化添加到i
:
int i=0, j=0;
scanf
返回成功读取次数。将返回值检查添加到scanf
:
int r = scanf("%d",&i); // Will return 1 if 1 argument was successully read
if(r == 1 && i == 10)
{
//do something
}
修改强>
正如其他人所指出的那样,如果输入错误,scanf
似乎不会消耗传入的字节。因此,您可能希望将其替换为fgets
和sscanf
:
int r;
char temp[32];
fgets(temp, 32, stdin); // Read input to temporary buffer
r = sscanf(temp, "%d", &i); // Try to convert value on buffer
if(r == 1 && i == 10)
{
//do something
}