C语言中的getchar 和 putchar 宏

getchar,顾名思义是get一个char,怎么能读如整数呢?
同样的,putchar是put一个char,当然不会是将整数输出。

不过,因为计算机从来不区分谁是整数谁是char,所以事情变成这样:

getchar函数,不需要参数,返回值是整型,功能是从标准输入的缓冲区“pop”出一个字符,而因为字符存储时是存储的字符的ASCII码,也就是一数字,所以getchar返回的整数就是这个字符的ASCII码;而因为C99要求getchar在遇到EOF时返回EOF,而EOF一般为-1,所以用char型数据类型无法标示,于是决定采用返回整型的实现方式。
7.19.7.6 The getchar function
Synopsis
1 #include <stdio.h>
int getchar(void);
Description
2 The getchar function is equivalent to getc with the argument stdin.
Returns
3 The getchar function returns the next character from the input stream pointed to by
stdin. If the stream is at end-of-file, the end-of-file indicator for the stream is set and
getchar returns EOF. If a read error occurs, the error indicator for the stream is set and
getchar returns EOF.
putchar函数,需要一个整型参数,返回整型;执行时,函数将传入的整型参数类型转换为unsigned char,并将其写入标准输出的缓冲区,然后将这个字符返回,(或者是EOF),用整型的原因同上。
7.19.7.9 The putchar function
Synopsis
1 #include <stdio.h>
int putchar(int c);
Description
2 The putchar function is equivalent to putc with the second argument stdout.
Returns
3 The putchar function returns the character written. If a write error occurs, the error
indicator for the stream is set and putchar returns EOF.

正如上面C99文档中提到的,一般的实现中,getchar和putchar一般都是宏,最终的调用是fgetc和fputc,针对标准输入和标准输出。所有的操作仅对于缓冲区的一个字符,或者说一个字节这么大的数据。

相关推荐