C 语言的 getchar() 函数和 putchar() 函数

getchar() 函数和 putchar() 函数是一对字符输入和输出函数.

getchar()

作用:get a character from stdin

原型:int getchar( void );

Required Header:<stdio.h>

Compatibility:ANSI

Return value:returns the character read. To indicate an read error or end-of-file condition, getchar returns EOF. For getchar, use ferror or feof to check for an error or for end of file.

The getchar() function takes no arguments, and it returns the next character from input.

代码示例:

c 复制代码
#include<stdio.h>

int main(void)
{
	char c;
	c = getchar();  // 读取一个字符输入,并将其赋值给 c
	getchar();      // 读取一个字符输入,但什么也不做,相当于丢弃了这个字符

	return 0;
}

下面这两行代码效果相同:

c 复制代码
c = getchar();
scanf("%c", &c);

putchar()

作用:Writes a character to stdout.

原型:int putchar( int c );

注意 c 的类型是 int.

Parameters:c:Character to be written

Required Header:<stdio.h>

Compatibility:ANSI

Return Value:returns the character written. To indicate an error or end-of-file condition, putchar return EOF; . Use ferror or feof to check for an error or end of file.

putchar() 函数打印它的参数.

下面这条语句把 c 的值作为字符打印出来:

c 复制代码
putchar(c);

这条语句和下面这条语句效果相同:

c 复制代码
printf("%c", c);

putchar() 不会自动换行.

即便传递给 putchar() 一个整数, 也会被转换为字符打印.

程序示例:

c 复制代码
#include<stdio.h>

int main(void)
{
	char c = 97;
	putchar(c);
	printf("%c", 97);

	return 0;
}

结果:

复制代码
aa

Because these functions deal only with characters, they are faster and more compact than the more general scanf() and printf() functions. Also, note that they don't need format specifiers; that's because they work with characters only. Both functions are typically defined in the stdio.h file. Also, typically, they are preprocessor macros rather than true functions.

程序示例:

输出一串字符, 如果是空格就原样输出, 否则输出它在字符表中的下一个字符.

c 复制代码
#include<stdio.h>
#include<ctype.h>

int main(void)
{
	char ch;
	while ((ch = getchar()) != '\n')
	{
		if (isspace(ch))
			printf("%c", ch);
		else
			printf("%c", ch + 1);  // 再次演示了字符实际上是作为数字存储的
	}
	printf("%c", ch);


	return 0;
}

结果:

复制代码
ok hello morning
pl ifmmp npsojoh
相关推荐
yueyuexiaokeai15 小时前
linux kernel常用函数整理
linux·c语言
想放学的刺客6 小时前
单片机嵌入式试题(第29期)嵌入式系统的电源完整性设计与去耦电容选型。抗干扰设计与EMC合规性
c语言·stm32·嵌入式硬件·物联网·51单片机
集芯微电科技有限公司9 小时前
15V/2A同步开关型降压单节/双节锂电池充电管理IC支持输入适配器 DPM 功能
c语言·开发语言·stm32·单片机·嵌入式硬件·电脑
zz345729811311 小时前
c语言基础概念9
c语言·开发语言
v_for_van12 小时前
力扣刷题记录4(无算法背景,纯C语言)
c语言·算法·leetcode
启友玩AI12 小时前
方言守护者:基于启英泰伦CI-F162GS02J芯片的“能听懂乡音”的智能夜灯DIY全攻略
c语言·人工智能·嵌入式硬件·ai·语音识别·pcb工艺
EmbedLinX13 小时前
Linux 之设备驱动
linux·服务器·c语言
小柯博客13 小时前
从零开始打造 OpenSTLinux 6.6 Yocto 系统 - STM32MP2(基于STM32CubeMX)(六)
c语言·git·stm32·单片机·嵌入式硬件·开源·yocto
你怎么知道我是队长14 小时前
C语言---排序算法6---递归归并排序法
c语言·算法·排序算法
梵刹古音14 小时前
【C语言】 字符数组与多维数组
c语言·数据结构·算法