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

文章目录


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

Typically, getchar() and putchar() are not true functions, but are defined using preprocessor macros.
通常,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.

getchar() 会读取每一个字符, 包括空白.

代码示例:

#include<stdio.h>

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

	return 0;
}

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

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 的值作为字符打印出来:

putchar(c);

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

printf("%c", c);

putchar() 不会自动换行.

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

程序示例:

#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.

程序示例:

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

#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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值