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
相关推荐
黎明smaly1 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
LIN-JUN-WEI3 小时前
[ESP32]VSCODE+ESP-IDF环境搭建及blink例程尝试(win10 win11均配置成功)
c语言·开发语言·ide·vscode·单片机·学习·编辑器
艾莉丝努力练剑5 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
黑听人5 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
看到我,请让我去学习11 小时前
OpenCV编程- (图像基础处理:噪声、滤波、直方图与边缘检测)
c语言·c++·人工智能·opencv·计算机视觉
倔强的小石头_13 小时前
【C语言指南】函数指针深度解析
java·c语言·算法
jz_ddk19 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
无小道20 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
FirstFrost --sy1 天前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森1 天前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机