#include <stdio.h>
#define CLEAR_BUFFER do { \
int c_tmp; \
while ((c_tmp = getchar()) != EOF && c_tmp != '\n'); \
} while (0)
/*
#define CLEAR_BUFFER do { \
for (int c_tmp; ((c_tmp = getchar()) != EOF && c_tmp != '\n'); ); \
} while (0)
*/
int main(){
char opt;
int retry;
do {
retry = 0;
printf("Do you want to delete all saved areas?(y/n):");
//setbuf(stdin, NULL); //试了setbuff、fflush都不行
//fflush(stdin);
scanf(" %c", &opt);
//printf("%d\n", opt);
//getchar();
CLEAR_BUFFER;
if (opt == 'y') {
return 1;
} else if (opt != 'y' && opt != 'n') {
retry = 1;
printf("error! Please input 'y' or 'n'!\n");
continue;
}
} while(retry);
return 0;
}
方法二:
1)空白字符
空白字符会使scanf()函数在读操作中略去输入中的一个或多个空白字符,空白符可以是space,tab,newline等等,直到第一个非空白符出现为止。
2) 非空白字符
一个非空白字符会使scanf()函数在读入时剔除掉与这个非空白字符相同的字符。
解决方案是使用以下内容消耗额外的换行符:
scanf(" %c", &yn);
^^^<------------Note the space
查了资料发现
1):
fflush(stdin);
fflush(stdin)在VC上可以使用,但是其他编译器不能保证对fflush的实现。
2):
setbuf(stdin, NULL);
setbuf(stdin, NULL);是使stdin输入流由默认缓冲区转为无缓冲区。但缓冲区没有了。
3):
char ch;while((ch = getchar()) != '\n' && ch != EOF);
这种方法使用的是C语言的基本语法,在什么情况都是支持的
参考:
https://codeday.me/bug/20190211/606768.html