嘿大家谢谢你的建议。不幸的是,我不允许使用此类功能。所以我写了这段代码,它适用于 1 个问题。如果我输入让我们说“hhjk”,它会吓坏的。我想在第一个'h'被检测为非数字后清除缓冲区..听说过函数 fflush 但我无法理解它..
int get_int()
{
char inp; /*inp, for input*/
int number; /*the same input but as integer*/
int flag=0; /*indicates if i need to ask for new input*/
do {
flag=0; /*indicates if i need to ask for new input*/
scanf("%c",&inp);
if (inp<48 || inp>57 ) /*this means it is not a number*/
{
inp=getchar(); /*Here i clear the buffer, the stdin for new input*/
printf("Try again...\n");
flag=1;
}
else
if (inp>53 && inp<58 && flag!=1) /*this means it is a number but not in the 0-5 range*/
{
inp=getchar(); /*here i clear the buffer, the stdin so i can get a new input*/
flag=1;
}
} while (flag);
number=inp-48; /*takes the ascii value of char and make it an integer*/
return number;
}