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;
}
答案 0 :(得分:4)
一种简单的方法是输入一个字符串,然后检查以确保其中的所有内容都是字符。我们可以使用strtol()
进行检查,因为它returns a 0 when it can't do the converstion,唯一的条件是因为你希望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;
}
答案 1 :(得分:1)
另一种方法是使用很少见的%[]格式用于scanf系列。在下面的代码中,我有%[0-9]。这只给我们数字。 (没有显示返回码等)
do {
if ((scanf("%[0-9]%c", input, &nl) == 2) && (nl == '\n')) {
value = strtol(input, NULL, 0);
} else {
value = -1;
}
} while ((0 <= value) && (value <= 5));