歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言中的getchar 和 putchar 宏

C語言中的getchar 和 putchar 宏

日期:2017/3/1 10:39:50   编辑:Linux編程

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,針對標准輸入和標准輸出。所有的操作僅對於緩沖區的一個字符,或者說一個字節這麼大的數據。

Copyright © Linux教程網 All Rights Reserved