scanf不会停止等待输入

本文探讨了C语言中使用scanf函数后残留输入缓冲区的问题,并提供了多种有效解决策略,包括定义宏来清空缓冲区,使用空白字符和非空白字符的方法,以及为何fflush和setbuf不一定适用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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://blog.csdn.net/agonie201218/article/details/47066887

https://blog.csdn.net/wkwk7600/article/details/83418109

https://blog.csdn.net/21aspnet/article/details/174326

https://blog.csdn.net/qq_26768741/article/details/50933598

https://www.cnblogs.com/codingmylife/archive/2010/04/18/1714954.html

https://codeday.me/bug/20190211/606768.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值