输入退出条件后陷入无限循环。

时间:2014-10-16 16:14:16

标签: c arrays if-statement while-loop

我试图在循环中运行,直到给出非数字输入。问题是,当我输入一个字母退出while循环时,它进入一个无限循环。它也进入第一个if语句并继续循环。如果有人对如何解决这个问题有任何想法,那就太好了。

int counter;
int input[100]
int num = 1
while (input[num] == 0)
{
    printf("score #%d:", counter);
    scanf("%d",&input[num]);

    if (input[num] <= 0){
        printf("you cannot use negative numbers\n");
        continue;
    }
    if (input[num] >= 100){
        printf("you cannot use numbers greater than 100\n");
        continue;
    }
    num++;
    counter++;

}

2 个答案:

答案 0 :(得分:4)

问题在于,当您尝试使用scanf格式进行读取时,%d提供了非数字输入时,非数字数据不会从缓冲区中删除。当你的循环再次达到scanf时,它会获得相同的数据,并在无限循环中继续失败。

要解决此问题,请在scanf未读取正确数量的项目时删除非数字输入:

int readCount = scanf("%d",&input[num]);
if (readCount != 1) {
    scanf("%*s");
    printf("Please enter a valid number.\n");
    continue;
}

请注意,循环的结束条件不正确,因为num总是超过已读取的最后一个元素。你可以像这样解决它:

while (num < 100)
{
    ... // Read and error checks go here
    if (input[num] == 0) {
        break;
    }
    num++;
    counter++;
}

答案 1 :(得分:2)

首先,num应该为0,因为数组索引从0开始而不是1。

然后,input[num]==0中的条件为while。您使用未初始化的变量进行测试,因为input尚未初始化。这与counter相同。

您的代码无法编译,因为您错过了第2行和第3行末尾的;

最后,使用以下代码替换scanf

if(scanf("%d",&input[num])==0)
{printf("non-numeric character entered .Exiting loop...\n");
scanf("%*s");// asterick tells scanf to discard scanned string(clear the entered char)
break;
}

最后,修改后的代码:

int counter=1; // initialize variable
int input[100]; //semicolon here
int num = 0; //num must be 0
while (1) //infinite loop
{
    printf("score #%d:", counter);

    if(scanf("%d",&input[num])==0) //if no value is scanned
{printf("non-numeric character entered .Exiting loop...\n");
scanf("%*s");// asterick tells scanf to discard scanned string(clear the entered char)
break;
}

    if (input[num] <= 0 )
        printf("you cannot use negative numbers\n");

    else if (input[num] >= 100)
        printf("you cannot use numbers greater than 100\n");
   else{
    num++;
    counter++;}

}