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
相关推荐
工藤新一¹16 分钟前
C/C++ 数据结构 —— 树(2)
c语言·数据结构·c++·二叉树··c/c++
kyle~5 小时前
C/C++---浮点数与整形的转换,为什么使用sqrt函数时,要给参数加上一个极小的小数(如1e-6)
c语言·开发语言·c++
用户6120414922138 小时前
C语言做的排队叫号系统
c语言·后端·敏捷开发
JasmineX-18 小时前
STM32的Sg90舵机
c语言·stm32·单片机·嵌入式硬件
XH华15 小时前
C语言第十一章内存在数据中的存储
c语言·开发语言
3壹18 小时前
单链表:数据结构中的高效指针艺术
c语言·开发语言·数据结构
knd_max20 小时前
C语言:内存函数
c语言
YLCHUP20 小时前
【联通分量】题解:P13823 「Diligent-OI R2 C」所谓伊人_连通分量_最短路_01bfs_图论_C++算法竞赛
c语言·数据结构·c++·算法·图论·广度优先·图搜索算法
特立独行的猫a1 天前
C/C++三方库移植到HarmonyOS平台详细教程
c语言·c++·harmonyos·napi·三方库·aki
啟明起鸣1 天前
【数据结构】B 树——高度近似可”独木成林“的榕树——详细解说与其 C 代码实现
c语言·开发语言·数据结构