gpt4 book ai didi

c - 如何限制只能输入一个字母?

转载 作者:行者123 更新时间:2023-11-30 15:05:29 24 4
gpt4 key购买 nike

我意识到,如果输入是以“y”或“n”开头的单词,它将跳出循环。如何限制循环,使其继续循环,除非输入是单个字符?

do
{
printf("Do you want to try again? (Y/N): ");
fflush(stdin);
scanf("%c", &repeat);
repeat = toupper(repeat);
if (repeat != 'Y' && repeat != 'N')
printf("Invalid answer. Please enter 'Y' or 'N'.\n\n");

} while (repeat != 'N' && repeat != 'Y');

最佳答案

像这样:

#include <stdio.h>
#include <ctype.h>

int main(void){
char repeat[3] = {0};//3 : one character + one character + NUL
do{
printf("Do you want to try again? (Y/N): ");fflush(stdout);
if(EOF==scanf("%2s", repeat)){ *repeat = 'N'; break; }
*repeat = toupper(*repeat);
if (repeat[1] || *repeat != 'Y' && *repeat != 'N'){//repeat[1] != '\0'..
printf("Invalid answer. Please enter 'Y' or 'N'.\n\n");
scanf("%*[^\n]");scanf("%*c");//clear upto newline
*repeat = 0;
}
} while (*repeat != 'N' && *repeat != 'Y');
puts("Bye!");//try agein or see ya, bye
return 0;
}

关于c - 如何限制只能输入一个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com