用户需要输入一个整数,然后回车。如果通过验证,则应返回整数,如果未通过验证,则用户应收到错误消息。
当我尝试通过 getInt()
函数验证输入时,我在键入 1 个或多个字符时遇到无限循环。当我键入 abc
时,我得到错误消息的无限循环,而输入 1a
得到正确的验证(1 条错误消息)。我遵循了这个流程图的指示:
代码
#include <stdio.h>
void clrKyb(void){
char input;
do {
scanf("%c",&input);
} while(input !='\n');
}
int getInt(void){
char NL= 'x' ;
int value ;
while(NL!='\n'){
scanf("%d%c",&value,&NL);
if(NL!='\n') {
void clrKyb(void);
printf("Invalid integer, please try again:");
}
}
return value ;
}
int main(void) {
int iVal;
printf("Enter an integer: ");
iVal = getInt();
printf("You entered: %d\n", iVal);
return 0;
}
最佳答案
如评论中所述:
- 在
getInt
中,void clrKyb(void);
应该只是clrKyb();
,因为你想使用clrKyb
你已经定义好了。
- 请注意,在
clrKyB()
(和getInt()
)中,您需要检查scanf()
的返回值。如果它返回 EOF,那么再多的重试等也无法阻止无限循环。 (正如 cxw 所指出的,目前在getInt()
中,您(重新)声明clrKyB()
并且不调用它 — 这也是一个问题。)
关于c - 整数验证给出无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289857/