我是 C 语言的初学者,我试图在数字中输入一个范围,但是当输入超出范围的字母时(例如:p),就会出现无限循环。 如果我输入的数字超出范围,它就会起作用。 我读到了有关内容,我认为这是缓冲区和函数 scanf 的问题,当我按“Enter”时,我包含\n。所以我尝试用字符扫描来清理,但没有成功。 我还尝试在 %x 之前添加一个空格(' '),但没有成功。 scanf 在我输入无效字母后它被忽略了;如果我输入无效的数字,程序就会运行。
#include <stdio.h>
int main()
{
int validity, pos; //validity 0:not valid, repeat the loop; validity 1: valid number
char enter;
while (validity == 0) {
printf("Player1 1, type the position in hexadecimal (1 to f):\n");
scanf(" %x%c", &pos, &enter); //here, the number pos is already in decimal
if (pos == NULL){
pos = 99; //if the letter typed is improper, I set 99, because is out of range
}
if(pos<=15 && pos >=0){
validity = 1;
} else {
printf("Invalid number, out of range\n");
validity = 0;
}
}
}
最佳答案
在循环中第一次,validity
根本没有定义的值。
可能是1
,可能是0
,也可能是65,532
。
您应该为其分配一个初始值。
int validity = 0, pos; //validity 0:not valid, repeat the loop; validity 1: valid number
<小时/>
您将 pos
声明为 int
;它永远不会是NULL
。它将具有整数值。
这一行没有意义:
if (pos == NULL){
您也应该初始化该变量。
int validity = 0, pos = 99; //validity 0:not valid, repeat the loop; validity 1: valid number
关于c - while 循环中带有 scanf 的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49663378/