c - 在我提示用户继续后,它以某种方式跳过我的键盘缓冲区,让我输入我想要的任何内容

标签 c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void buffer();

int fib(int x, int y) {
    if (y <= 1) {
        return x;
    } else {
        return fib(x, y - 1) + fib(x, y - 2);
    }
}

int main(int argc, char * argv[]) {
    int x;
    int y;
    char answer = 'y';

    while (answer == 'y') {
        printf("Please enter the initial value of the green curd: ");
        scanf("%d", &x);
        buffer();

        while (x < 1) {
            printf("I'm sorry that value is unrecognized or is negative.\n");
            printf("Please enter the initial value of the green curd: ");
            scanf("%d", &x);
            buffer();
        }

        printf("Please enter the number of days: ");
        scanf("%d", &y);
        buffer();

        while (y < 1) {
            printf("I'm sorry that value is unrecognized or is negative.\n");
            printf("Please enter the number of days: ");
            scanf("%d", &y);
            buffer();
        } 

        printf("With the initial population of %d pounds of crud growing for %d days.\n", x, y);
        printf("The final population would be %d pounds.\n", fib(x, y / 5));
        printf("Would you like to continue? (y/n): ");
        scanf("%c", &answer);
        buffer();

        while (answer != 'y') {
            if (answer == 'n') {
                exit(1);
            }

            printf("I'm sorry that value is unrecognized or is negative.\n");
            printf("Would you like to continue? (y/n): ");
            scanf("%c", &answer);
            buffer();   
        }        
    }

    return 0
}

 void buffer(void) {
     char ch;
     scanf("%c", &ch);

     while (ch != '\n') {
         scanf("%c", &ch);
     }
 }

我有一个项目要交到学校。只是寻求一些建议。程序运行良好,但是当我决定继续时,缓冲区语句不会阻止我第二次输入字符。只有当我到达末尾继续时,程序实际上使用我的 while 循环来停止任何无效输入。

最佳答案

scanf("%d", &y);

将换行符保留在输入缓冲区中,然后立即由以下内容拾取

scanf("%c", &answer);

您应该让 scanf() 通过在格式字符串前插入一个空格来跳过空格,其中包括换行符

scanf(" %c", &answer);

关于c - 在我提示用户继续后,它以某种方式跳过我的键盘缓冲区,让我输入我想要的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49912599/

相关文章:

c - 切换编译器和 IDE 后在 C 中位打包结构的语法错误

c - C语言更新记录

c - 为什么我收到错误 "cannot find -lncurses"?

c - int *x[10] 和 int (*x)[10] 的区别

CMake 适用于 Mac,但不适用于 Linux?

c - 具有多个子节点和下一个节点的树

java - 从 Windows 上的 C 中检测 32/64 位 Java

c++ - 磁盘数据库如何在文件系统级别处理文件读写?

C++ mktime 返回随机日期

c - 为 __uint128 数字预处理 C 十六进制字符串