C 在我提示用户继续之后,不知何故它跳过了我的键盘缓冲区,让我输入我想要的任何内容

C 在我提示用户继续之后,不知何故它跳过了我的键盘缓冲区,让我输入我想要的任何内容,c,C,我有一个项目要交给学校。只是想寻求一些建议。程序运行正常,但当我决定继续时,缓冲区语句并没有阻止我第二次输入字符。只有当我到达终点继续时,程序才会使用while循环来停止任何无效的输入 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> void buffer(); int fib(int x, int y) { if (y <= 1) { return x; } else {

我有一个项目要交给学校。只是想寻求一些建议。程序运行正常,但当我决定继续时,缓冲区语句并没有阻止我第二次输入字符。只有当我到达终点继续时,程序才会使用while循环来停止任何无效的输入

#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);
     }
 }
将在输入缓冲区中保留换行符,然后由下面的

scanf("%d", &y);
您应该通过在格式字符串之前插入空格,使scanf跳过包含换行符的空白

scanf("%c", &answer);

扫描%c,&answer;=>扫描%c,&answer;添加空格提示:阅读scanf-有很多。你认为在每个数字后输入的回车键会发生什么变化?如果您使用调试器逐行检查代码,并在scanf调用后检查答案的内容,您将知道问题所在。编程新手,第一学期。我在VB中使用调试器,只是因为某种原因无法找出问题所在。谢谢你的建议,非常感谢。非常感谢。
scanf(" %c", &answer);