【发布时间】:2018-04-05 02:51:32
【问题描述】:
我是 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;
}
}
}
【问题讨论】:
-
在使用
pos之前检查scanf(" %x%c", &pos, &enter)的返回值。至少是 1 个吗? -
“我试图用一个字符扫描来清理,但是没有用”——代码不这样做。如果
"%x"成功,scanf()只会移动到"%c"。
标签: c