#include <stdio.h>
#include <stdlib.h>
/*
* GETOP -- get an integer operand; we do operation-specific checks later
*
* parameters: opno the number of the operand (as in 1st, 2nd, etc.)
* returns: int the integer value of the operand just read
* exceptions: none */
int getop(int opno)
{
int val;
int rv; /* value returned from scanf */
/* a
* loop until you get an integer or EOF
*
* prompt and read a value */
do{
/* prompt and read a value */
printf("\toperand %d: ", opno);
rv = scanf("%d", &val);
/* oops */
if (rv == 0)
{
printf("\toperand must be an integer\n");
/* loop until a valid value */
}
while (rv == 0);
/*
* if it's EOF, say so and quit
*/
if (rv == EOF)
{
exit(EXIT_SUCCESS);
}
/*
* otherwise, say what you read
*/
return(val);
}
/ *当我写rv == 0时,它一直给我一个无限循环。我写错了什么或是否有其他方法来检查非整数而没有程序进入无限循环? * /
答案 0 :(得分:2)
因为当scanf
看到与其格式不匹配的输入时,它只是停止读取,并将无效输入留在缓冲区中。因此,下次尝试阅读时,您将再次尝试读取完全相同的无效输入,并再次...
一个简单的解决方案是使用fgets
读取一行,然后使用sscanf
获取数据。