当前位置:网站首页>scanf()和getchar()的用法讨论
scanf()和getchar()的用法讨论
2022-07-23 18:41:00 【仙人掌也会开花】
首先我们了解一下scanf和getchar的用法.
getchar()
getchar()是stdio.h中的库函数,它的作用是从缓冲区中读入一个字符,也就是说,如果缓冲区有数据的话不用输入它就可以直接读取了,第一次调用getchar()时,确实需要人工的输入,但是如果你输了多个字符,以后的getchar()再执行时就会直接从缓冲区中读取了
与scanf不同,getchar()能够读取空格、回车等. 而scanf遇到空格与回车时,会结束读取.
一般scanf读走输入数据后,会留下如\n等的字符,而如果我们还要再次调用scanf的话,缓冲区中还有\n,此时scanf不等我们输入数据,就直接把\n读走了,从而不能达到我们的目的。
所以,在如下判断你输入的是否是字母的代码中,需要用getchar()来接受那个被放到缓冲区的空格或者回车,否则的话,scanf下一次接受的就是空格或者回车,而非你输入的字符了

那除了用getchar()接收缓冲区里面的空格或回车,还有什么办法呢?
还有一个方法是,在%c前面加空格,意思是跳过下一个字符前的所有空白字符.

同时,你可能会对以下代码产生疑问,明明同样是循环的办法输入,为什么在前面的while循环语句中需要用getchar()来接收空白字符,而在下面的for循环语句中不需要写getchar呢?

通过请教老陈,我知道原来空格是区分数字的,%c不会,也就是说%c会保存空格,但%d+空格的时候,空格并不会在缓存区~.
结语:这是今天的分享,感谢老陈的回答给我一种醍醐灌顶的感觉~
我是仙人掌,在厦门软件学院读大二的学生,如果这篇文章给你帮助的话,可不可以给个一键三连呢,把这篇文章传递给更多需要他的人~
边栏推荐
- 项目实战第九讲--运营导入导出工具
- Powercli management VMware vCenter batch deployment export import
- redis过期key的删除策略[通俗易懂]
- 使用 mysqldump 或 mydumper 配置 MySQL 主从复制
- Robot decision-making system based on self-learning (daki technology, Zhao kaiyong)
- 【AR学习】-- 二、 环境搭建
- Relevant interfaces of [asp.net core] option mode
- 家用 NAS 服务器(3)| SSD缓存加速机械硬盘
- 【无标题】
- Cannot read properties of null (reading ‘pickAlgorithm‘)
猜你喜欢

AtCoder——Subtree K-th Max

Robot decision-making system based on self-learning (daki technology, Zhao kaiyong)

Energy principle and variational method note 14: summary + problem solving

【无标题】

【AR学习】-- 二、 环境搭建

能量原理与变分法笔记12:最小势能原理

I deliberately leave a loophole in the code. Is it illegal?

Element positioning in selenium is correct, but the operation fails. Six solutions are all finalized
![Educational codeforces round 132 (rated for Div. 2) [competition record]](/img/7d/ef0df3e0d772b17264beb9c189a3c2.png)
Educational codeforces round 132 (rated for Div. 2) [competition record]

web安全入门-ssh测试与防御
随机推荐
MySQL master-slave replication
redis过期key的删除策略[通俗易懂]
能量原理与变分法笔记16:虚位移原理的求解
Leetcode 152. 乘积最大子数组(暴力破解居然可以通过!)
2、 MFC windows and messages
[激光器原理与应用-8]: 激光器电路的电磁兼容性EMC设计
李鸿章 临终诗 临终奏折 全文
3D point cloud course (VI) -- 3D target detection
The full text of Li Hongzhang's deathbed poem
Detailed writing process of impala
Ggarrange function of R language ggpubr package combines and annotates multiple images_ Figure add annotation, annotation, annotation information to the combined image, and add annotation information
3D point cloud course (VII) -- feature point description
Construction deployment scheme of GPS Beidou clock server (NTP network clock system)
White paper on adaptive robot interaction
Redux求和案例详解版教程
web安全入门-ssh测试与防御
千呼万唤,5G双卡双通到底有多重要?
osgearth2.8编译siverlining云效果
Codeworks round 805-808 [partial solution]
2022 Shandong old age Expo, Shandong elderly care exhibition, China International elderly care service industry exhibition was held in September