【发布时间】:2020-05-23 16:35:24
【问题描述】:
所以我有一些这样的代码(请注意这是在 C89 中):
void inputChoice(int* choicePtr)
{
int choice;
printf(BLUE "\nINPUT: " RESET); /* Print input using the ansi colour code for Blue. */
scanf("%d", &choice); /* Parse the choice. */
while ((choice < 1) && (choice > 5)) /* Loop until choice is one of the menu options. */
{
/* Request for a valid menu option, printing this using the ansi colour code for Red, then resetting back to the default colour. */
printf(RED "\nMenu Selection must be between (1 and 5) inclusive. \nPlease Re-enter. \n" RESET);
scanf("%d", &choice); /* Parse the choice. */
}
*choicePtr = choice; /* Set the choice pointer to the valid choice after validation. */
}
选择哪个。它适用于整数。但如果有人输入其他任何内容,例如字符。它无限循环。 我想以某种方式检查是否输入了字符。
我尝试过的一种方法是添加它以检查是否输入了字符,因为如果扫描不正确,整数将为 0。
如下所示,但这也不起作用:
scanf("%d", &choice);
while (choice == 0)
{
printf("Invalid Choice Re-enter.");
scanf("%d", &choice);
}
【问题讨论】:
-
检查什么
scanfreturns。 -
使用
fgets()读取用户输入。
标签: c validation user-input infinite-loop c89