C中的无限循环BUG

时间:2015-11-09 20:06:55

标签: c loops debugging

这是计算器程序中的一项功能。如果用户键入非数字,则循环操作数1“必须是整数”将变为无限。

我知道while循环有问题,但我不知道如何修复它。 HELP ????

int getop(int opno)
{
int val;        /* value read */
int rv;         /* value returned from scanf */
int *rv1 = &rv;
/*
 * loop until you get an integer or EOF
 */
do {
    /* prompt and read a value */
    printf("\toperand %d: ", opno);
    rv = scanf("%d", &val);
    /* oops ... bogus value */
    if (rv == 0)
        printf("\toperand must be an integer\n");
    /* loop until a valid value */
} while (*rv1 == 0);
/*
 * if it's EOF, say so and quit
 */
if (rv == EOF)
    exit(EXIT_SUCCESS);

/*
 * otherwise, say what you read
 */
return(val);
}


int main(void)
{
int ch;         /* input character */
int op;         /* operation, derived from ch */
int op1, op2;       /* operands */
int result;     /* result to be printed */


/*
 * prompt the user for an operation
 */
printf("operation (+,-,*,/,%%)> ");

/*
 * loop until user says to quit
 */
while((ch = getchar()) != EOF){
    /* convert the character read to an operator */
    if ((op = valop(ch)) == ERROR){
        /* eat the rest of the line */
        while(ch != '\n' && (ch = getchar()) != EOF)
            ;
        printf("operation (+,-,*,/,%%)> ");
        continue;
    }
    /* get the operands */
    op1 = getop(1);
    op2 = getop(2);
    /*
     * if division operation by 0, complain
     * otherwise do the operation
     */
    if (isdivop(op) && op2 == 0)
        fprintf(stderr, "Can't have a denominator of 0\n");
    else{
        result = apply(op1, op, op2);
        printf("%d %c %d = %d\n", op1, ch, op2, result);
    }
    /* eat the rest of the line */
    while(ch != '\n' && (ch = getchar()) != EOF)
        ;
    /* prompt again */
    printf("operation (+,-,*,/,%%)> ");
   }
  putchar('\n');

 return(EXIT_SUCCESS);
 }

1 个答案:

答案 0 :(得分:1)

如果输入非数字数据,则没有任何内容与%d格式说明符匹配,输入将保留在缓冲区中。因此,每次循环时,它都会继续尝试读取相同的无效数据,从而导致无限循环。

(rv==0)的情况下,您需要通过循环调用getchar()来刷新缓冲区,直到获得换行符:

if (rv == 0) {
    printf("\toperand must be an integer\n");
    while (getchar() != '\n');
}