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\n");
        printf("Do you want to continue(Y/N) ?");
        scanf(" %c", &answer);
    }
    return 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
}

关于c - 如何减少多个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431862/

相关文章:

c - 如何在C中将静态数组的所有元素重置为0

c - 没有这样的文件或目录和段错误 - 打开文件

尽可能快地比较缓冲区

c - 即使在我释放它之后,Valgrind 也发现了字符串的内存泄漏

创建具有定义大小的文件

c - 最新的系统日志消息被延迟

将手动输入的字符串与用户输入的字符串进行比较

c++ - 如何将 if 语句更改为 switch

c++ - 避免在 C++ 库中使用全局对象

c - C 中二进制搜索的第一次和最后一次出现