#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时,它一直给我一个无限循环。我是不是写错了,或者有没有别的方法可以在程序不进入无限循环的情况下检查非整数?*/
最佳答案
因为当scanf
看到与其格式不匹配的输入时,它只会停止读取,并将无效输入留在缓冲区中。所以下次你试着读的时候,你会一次又一次地读同样的无效输入,然后。。。
一个简单的解决方案是使用fgets
读取行,然后使用sscanf
获取数据。