【发布时间】:2019-12-19 17:22:17
【问题描述】:
我编写这个程序来验证用户输入的选择(整数类型变量)。但问题是在有效输入之后,下一个无效输入(例如:字符类型变量)将不会存储在整数变量(选择)中。我该如何解决这个问题?
#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("Invalid\n");
else break;
}
printf("Success\n");
}
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;
}
}
【问题讨论】:
-
不是一个答案,但是如果你从来没有给它赋值,你为什么要传递一个指向
selectionCheck()的指针?,只需传递一个int
标签: c validation integer character