#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/