当前位置:网站首页>用getchar清理缓冲区(强烈推荐,C语言易错典型)
用getchar清理缓冲区(强烈推荐,C语言易错典型)
2022-07-23 05:39:00 【rookieﻬ°】
如何清理缓冲区??
什么是缓冲区?
缓冲区又称为缓存,是内存中的一部分,是内存中预留的储存空间,用来缓冲输入或输出的数据。根据其对应的输出设备还是输出设备,分为输入缓冲区和输出缓冲区。
为什么要清理缓冲区?
我们在磁盘中读取信息时,会先把读出的数据放入缓冲区,计算机再从缓冲区读取数据,当缓冲区中的数据被读取完毕时,计算机又会根据需求重复进行上部分操作,直到用户读取结束。但是,当我们不需要缓冲区的内容而想跳过它,直接读取下一部分内容时,我们能直接读取吗?显然是不可以的!这时候就要我们清理缓冲区了;
如何清理缓冲区?
例:判断是否能正常运行?
#include<stido.h>
int main()
{
char password[10] = {
0};
printf("请输入密码:\n");
scanf("%s",password);//数组名就是地址,这一点要记住哦
printf("请确认密码(Y/N):");
int ch = gerchar();//getchar的返回类型为int型,如果设为char类型,有可能数据丢失
if(ch == 'Y')
{
printf("确认成功\n");
}
else
{
printf("确认失败\n");
}
return 0;
}
答案是:不能。
为什么呢?[^1]
[1^]:图取自小仙颖的emojil。
因为当你在scanf输入密码的之后,你的回车也被放到了缓冲区,但是scanf读取了回车之前的内容,却把回车符号留在了缓冲区,这就造成当你getchar()的时候,缓冲区是有东西的,因而getchar()直接读取了这个回车符。
解决方法:
步骤:
getchar();
这样可以清理缓冲区的一个字符,比如上一题;
那如果我想清理很多缓冲区的垃圾呢?这个时候就要用到循环了。
while(getchar()!='\0');
这个循环就非常简短精妙,你仔细分析,会发现,最后回车符也被清理了!
我想,朋友,你也不想别人白嫖你的文章吧【手动滑稽】。
边栏推荐
- 項目部署(簡版)
- Error when PLSQL creates Oracle Database: when using database control to configure the database, it is required to configure the listener in the current Oracle home directory. You must run netca to co
- The super simple face recognition API can realize face recognition in just a few lines of code
- 大厂面试机器学习算法(5)推荐系统算法
- 请求数据获取与响应
- Uscd pedestrian anomaly data set user guide | quick download
- Déploiement du projet (version abrégée)
- Redis database and project framework
- Using pytorch to realize the flower recognition classifier based on VGg 19 pre training model, the accuracy reaches 97%
- 视图集及路由
猜你喜欢

Install enterprise pycharm and Anaconda

给图片人脸部分加上马赛克

Pytorch white from zero uses North pointing

大厂面试机器学习算法(5)推荐系统算法

防止神经网络过拟合的五种方法
![[flink]flink on yarn之flink-conf最简单配置](/img/de/0ec23f3379148dba27fe77dc51e22f.png)
[flink]flink on yarn之flink-conf最简单配置

主从同步步骤读写分离+自遇错误分享

JDBC learning and simple encapsulation

项目部署(简版)

plsql创建Oracle数据库报错:使用Database Control配置数据库时,要求在当前Oracle主目录中配置监听程序 必须运行Netca以配置监听程序,然后才能继续。或者
随机推荐
Fun code rain, share it online~-
How to merge the website content with video and audio separated? How to write batch download code?
Using pytorch to realize the flower recognition classifier based on VGg 19 pre training model, the accuracy reaches 97%
PyGame realizes the airplane war game
开发必备之Idea使用
The super simple face recognition API can realize face recognition in just a few lines of code
Paging and filtering
2.启动函数返回值的剖析
请求数据获取与响应
【无标题】
主从同步步骤读写分离+自遇错误分享
Pywinauto+某应用程序(学习至第9讲)--受阻
Pyspark learning notes
[Python flask note 5] Blueprint simple à utiliser
js中拼接字符串,注意传参,若为字符串,则需要加转义字符
[flink]flink on yarn之flink-conf最简单配置
大米商城注册
Five methods to prevent over fitting of neural network
项目部署(简版)
[python flask notes 5] blueprint is easy to use