
4.5 字符数据的输入/输出
本节主要介绍putchar输出函数与getchar输入函数。
4.5.1 putchar函数
putchar函数是字符输出函数,putchar是put character(送出字符)的缩写,其功能是在显示器上输出单个字符,其一般形式为

函数原型:_Check_return_opt__CRTIMP int__cdecl putchar(_In_int_Ch);
说明:1)所谓函数原型是来自相应头文件(本章介绍的输入/输出函数来自stdio.h)的函数声明,这样的函数定义首部,其类型定义、函数参数定义等是最“原生态”的,因此,读者对函数可以看得更透彻、更清晰。
本书给出的是VC++2010的C语言函数原型,其他编译系统的函数原型与此类似。
2)_CRTIMP:是个宏定义,是C run time implement的简写,表示“C运行库的实现”,也就是标志此函数是个库函数。
3)int表示函数返回值是int型的,必须要有个输入参数类型也是整型的。
4)__cdecl:是C Declaration的缩写(declaration,声明),是一个编译规则标志宏定义,给编译器提供指示。有了这个标志,编译器在编译此函数时按照这个规范去编译。__cdecl表示C语言默认的函数调用方法:所有参数从右到左依次入栈,这些参数由调用者清除,称为手动清栈。被调用函数不会要求调用者传递多少参数,调用者传递过多或者过少的参数,甚至完全不同的参数都不会产生编译阶段的错误。
5)_Check_return_opt_、_In_也都是有一定指示意义的宏定义。
6)putchar(_In_int_Ch):函数名putchar,带一个int型参数,参数为字符的编码值。举例如下:

对控制字符则执行控制功能,不在屏幕上显示。举例如下:

使用本函数前必须要用文件包含命令:#include<stdio.h>或#include"stdio.h"。
【例4-2】输出单个字符。

运行结果:
4.5.2 getchar函数
getchar函数的功能是从键盘上输入一个字符。getchar是get character(获取字符)的缩写,其一般形式为

函数原型:_CRTIMP int__cdecl getchar(void);
通常它把输入的字符赋予一个字符变量,构成赋值语句,如"c=getchar();"。
【例4-3】输入单个字符并显示。

多次运行以上程序,体会getchar()函数读字符的功能。
注意:使用getchar函数还应注意以下几个问题。
1)getchar函数只能接受单个字符,输入数字也按字符处理。输入多于一个字符时,只接收第一个字符。
2)Win-TC中使用本函数前必须包含文件“stdio.h”。程序运行到本函数时,将等待用户输入。
3)一般键盘输入以回车键(〈Enter〉键)表示输入结束。为此,输入字符数往往是大于等于2,除非直接按〈Enter〉键。
上面程序最后两行可用下面两句的任意一句代替,是函数嵌套调用的紧凑形式。

【例4-4】输入单个字符并显示输入字符的ASCII码值。

若输入a并按〈Enter〉键,运行结果类似为: