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
相关推荐
是翔仔呐8 小时前
第11章 显示外设驱动:I2C协议OLED屏、SPI协议LCD屏字符/图片/中文显示
c语言·开发语言·stm32·单片机·嵌入式硬件·学习·gitee
木下~learning10 小时前
对于Linux中等待队列和工作队列的讲解和使用|RK3399
linux·c语言·网络·模块化编程·工作队列·等待队列
是翔仔呐11 小时前
第13章 SPI通信协议全解:底层时序、4种工作模式与W25Qxx Flash芯片读写实战
c语言·开发语言·stm32·单片机·嵌入式硬件·学习·gitee
IT方大同11 小时前
RT_thread(RTOS实时操作系统)线程的创建与切换
c语言·开发语言·嵌入式硬件
是翔仔呐11 小时前
第14章 CAN总线通信全解:底层原理、帧结构与双机CAN通信实战
c语言·开发语言·stm32·单片机·嵌入式硬件·学习·gitee
深邃-12 小时前
数据结构-队列
c语言·数据结构·c++·算法·html5
2301_8227828213 小时前
C语言数组通关攻略!从一维到字符数组,零基础也能轻松掌握
c语言·算法·数组·编程基础·避坑技巧
2301_8227828213 小时前
C3 vs Zig:2026年,谁才是真正能“修复”C语言的救星?
c语言·zig·c3·系统级开发·语言革新
星夜夏空9914 小时前
C语言进阶项目——搭建内存池
c语言·开发语言
聆风吟º15 小时前
【C标准库】深入理解 C 语言memmove函数:安全内存拷贝的利器
c语言·开发语言·memmove·库函数