C 如何减少多重输出

C 如何减少多重输出,c,C,当我输入多个字符时,如何将输出限制为仅一个响应 #include <stdio.h> main(){ char answer; printf("Do you want to continue(Y/N)?"); scanf("%c", &answer); while ((answer != 'Y') && (answer != 'N')){ printf("\nYou must type a Y or an N

当我输入多个字符时,如何将输出限制为仅一个响应

#include <stdio.h>
main(){
    char answer;

    printf("Do you want to continue(Y/N)?");
    scanf("%c", &answer);

    while ((answer != 'Y') && (answer != 'N')){
        printf("\nYou must type a Y or an N\n");
        printf("Do you want to continue(Y/N) ?");
        scanf(" %c", &answer);
    }
    return 0;
}
#包括
main(){
答案;
printf(“是否要继续(是/否)”;
scanf(“%c”和“应答”);
而((答案!='Y')&&(答案!='N')){
printf(“\N您必须键入Y或N”);
printf(“是否要继续(是/否)”;
scanf(“%c”和“应答”);
}
返回0;
}
使用getchar()读取第一个字符,然后读取下一个字符,直到EOF

此外,不需要在循环外部(之前)进行读数

#include <stdio.h>

// additional function for reading remaining input
void flush();

main(){

    // answer needs to be int, because getchar() can return -1 in case of EOF
    int answer; 

    while (1) {

        printf("Do you want to continue(Y/N)? ");
        answer = getchar();

        // read and ignore the remaining input
        flush();

        if ((answer == 'Y') || (answer == 'N'))
            break; // exit loop

        printf("\nYou must type a Y or an N\n");
    }

    // here answer contains 'Y' or 'N'
    // do what you need with this...

    return 0;
}

// function for consuming the remaining input
void flush()
{
    while (getchar() != EOF); // consume input until emptying
}
#包括
//用于读取剩余输入的附加功能
无效冲洗();
main(){
//答案必须是int,因为getchar()在EOF的情况下可以返回-1
int答案;
而(1){
printf(“是否要继续(是/否)”;
答案=getchar();
//读取并忽略剩余的输入
冲洗();
如果((答案='Y')| |(答案='N'))
break;//退出循环
printf(“\N您必须键入Y或N”);
}
//此处答案包含“Y”或“N”
//用这个做你需要的。。。
返回0;
}
//用于消耗剩余输入的函数
无效刷新()
{
while(getchar()!=EOF);//使用输入直到清空
}

您可以在scanf中使用%s格式,并在结果字符串中使用
strchr()
搜索“y”或“n”。通过使用
fgets
获取所有输入。如果它在某种程度上无效,请忘记它并输入另一个字符串。@Cubo78如何使用
strchr()
?第一个谷歌结果:。它是一个用于搜索字符串中第一个出现的字符的函数。注意:
while((answer!='Y')&&&(answer!='N')){…scanf('%c',&answer);}
是文件末尾的无限循环。最好测试
scanf()
的返回值。