在 C 程序中使用字符输入验证整数



我编写这个程序来验证用户输入的选择(整数类型变量(。但问题是在有效输入之后,下一个无效输入(例如:字符类型变量(将不会存储在整数变量(选择(中。我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#pragma warning (disable:4996)
void main()
{
int selection;
while (1)
{
while (1)
{
printf("Enter Your Selection (0-4) > ");
scanf("%d", &selection);
rewind(stdin);
if (!selectionCheck(&selection, 0, 4))
printf("Invalidn");
else break;
}
printf("Successn");
}
system("pause");
}
int selectionCheck(int *input, int min, int max)
{
char str[100] = "";
itoa(*input, str, 10);
if (isdigit(str[0]))
{
if (*input < min || *input > max)
return 0;
else return 1;
}
else
{
return 0;
}
}

一些注意事项: 1(您没有检查scanf()返回值,这是非常有用的:负返回值表示输入的字符无法转换为int(由于"%d"格式(,返回值等于0表示输入为空(未输入字符(。

2( 如果用户输入了错误的字符(不是数字(,输入缓冲区将保持忙碌状态,直到您以其他方式读取它。好主意是在此处使用其他scanf("%s")将任何字符读取为字符串,因此在此调用后缓冲区将为空。在这里使用rewind()是不够的。

3(不需要额外检查selectionChecking()中的输入isdigit(),因为scanf()中的"%d"格式不允许读取除数字以外的任何其他内容。

4( 无需在调用中传递指向selectionselectionChecking()指针 - 将其作为值传递就足够了。

因此,请在下面尝试此操作:

// declaration of 'selectionCheck()'
int selectionCheck(int input, int min, int max);
void main()
{
int selection;
while (1)
{
while (1)
{
printf("Enter Your Selection (0-4) > ");
int ret = scanf("%d", &selection);
if (ret < 0) // invalid characters on input
{
printf("Invalid charactersn");
scanf("%s"); // empty buffer, reading it as string and putting readed characters to nowhere ;)
continue; // go to top of loop
}
if (ret == 0) // empty input
{
printf("No (empty) inputn");
continue; // go to top of loop
}
// here 'ret' is greather than 0, so valid number was entered
if (selectionCheck(selection, 0, 4)) // is value between 0 and 4 ?
break; // yes, success, break current loop!
printf("Invalid valuen");
}
printf("Successn");
}
system("pause");
}
int selectionCheck(int input, int min, int max)
{
if (input < min || input > max)
return 0;
else 
return 1;
}

当然,你可以写'selectionCheck(('更精简:

int selectionCheck(int input, int min, int max)
{
return (input < min || input > max) ? 0 : 1;
}

或者简单地:

int selectionCheck(int input, int min, int max)
{
return (input >= min && input <= max);
}

最新更新