使用scanf()检测读取非数字
大家好,谢谢你们的建议。不幸的是,我不允许使用这些函数。所以我写了这段代码,它可以很好地解决1个问题。如果我进去,让我说“hhjk”,它会发疯的。我想在第一个“h”被检测为非数字后清除缓冲区。。听说过函数fflush,但我不能理解它使用scanf()检测读取非数字,c,scanf,C,Scanf,大家好,谢谢你们的建议。不幸的是,我不允许使用这些函数。所以我写了这段代码,它可以很好地解决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
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;
}
int get_int()
{
字符inp;/*inp,用于输入*/
int number;/*输入相同,但为整数*/
int flag=0;/*表示是否需要请求新输入*/
做{
flag=0;/*表示是否需要请求新输入*/
scanf(“%c”、&inp);
如果(inp57)/*这意味着它不是一个数字*/
{
inp=getchar();/*这里我清除了缓冲区,新输入的标准输入*/
printf(“重试…\n”);
flag=1;
}
其他的
如果(inp>53&&inp一种简单的方法是输入一个字符串,然后检查以确保其中的所有内容都是一个字符。我们可以使用strtol()
进行检查,因为它是有效的输入,唯一的条件是因为您希望0是有效的输入,我们必须在检查上设置一个特殊的条件:
int main()
{
char input[50]; // We'll input as a character to get anything the user types
long int i = 0;
do{
scanf("%s", input); // Get input as a string
i = strtol(input, NULL, 10); // Convert to int
if (i == 0 && input[0] != '0') { // if it's 0 either it was a numberic 0 or
printf("Non-numeric\n"); // it was not a number
i = -1; // stop from breaking out of while()
}
else if(i<0 || i > 5)
printf("wrong\n");
}while (i < 0 || i >5);
return 0;
}
intmain()
{
char-input[50];//我们将作为字符输入,以获取用户键入的任何内容
长整数i=0;
做{
scanf(“%s”,输入);//以字符串形式获取输入
i=strtol(输入,NULL,10);//转换为int
如果(i==0&&input[0]!='0'){//如果它是0,则它是数字0或
printf(“非数字的”;//它不是一个数字
i=-1;//停止从while()中断
}
若否(i)(5)
printf(“错误的\n”);
}而(i<0 | | i>5);
返回0;
}
另一种方法是对scanf系列使用罕见的%[]格式。在下面的代码中,我有%[0-9]。这只给出了数字。(没有显示返回代码等)
do{
如果((scanf(“%[0-9]%c”,输入,&nl)==2)和&(nl=='\n')){
值=strtol(输入,NULL,0);
}否则{
值=-1;
}
}当((0读取非数字时
那么,您想涵盖什么?所有和任何可能的错误输入?或者只是确保用户没有输入单个字符?如果他输入数字“8”,我需要打印“错误”,如果他输入,让我们说“j”,我需要忽略并等待新的输入
do {
if ((scanf("%[0-9]%c", input, &nl) == 2) && (nl == '\n')) {
value = strtol(input, NULL, 0);
} else {
value = -1;
}
} while ((0 <= value) && (value <= 5));