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

标签 c

我意识到,如果输入是以“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/

相关文章:

c - 结构对齐问题

c++ - 格式化标志检查的简洁方法

c - 为什么我输入两次 't' 时得到的是垃圾值?

C - 某些尺寸的 "sysmalloc: Assertion ..."错误

c++ - 了解 C 类型定义

c - 链接列表的一些帮助

c - 排序时间时结构和 qsort 不工作

c - while 循环会检查每个条件吗?

c - 为什么 malloc 真的是不确定的? (Linux/Unix)

c - 我的 sscanf 格式有什么问题