getchar
函數名: getchar
功 能: 從stdio流中讀字符
用 法: int getchar(void);
註解:
getchar有一個int型的返回值.當程序調用getchar時.程序就等着用戶按鍵.用戶輸入的字符被存放在鍵盤緩衝區中.直到用戶按回車爲止(回車字符也放在緩衝區中).當用戶鍵入回車之後,getchar纔開始從stdio流中每次讀入一個字符.getchar函數的返回值是用戶輸入的第一個字符的ASCII碼,如出錯返回-1,且將用戶輸入的字符回顯到屏幕.如用戶在按回車之前輸入了不止一個字符,其他字符會保留在鍵盤緩存區中,等待後續getchar調用讀取.也就是說,後續的getchar調用不會等待用戶按鍵,而直接讀取緩衝區中的字符,直到緩衝區中的字符讀完爲後,纔等待用戶按鍵.
getch與getchar基本功能相同,差別是getch直接從鍵盤獲取鍵值,不等待用戶按回車,只要用戶按一個鍵,getch就立刻返回, getch返回值是用戶輸入的ASCII碼,出錯返回-1.輸入的字符不會回顯在屏幕上.getch函數常用於程序調試中,在調試時,在關鍵位置顯示有關的結果以待查看,然後用getch函數暫停程序運行,當按任意鍵後程序繼續運行.
這個版本忽略了個重點,getch()是非緩衝輸入函數,就是不能用getch()來接受緩衝區已存在的字符,如以下C++程序,
int i;while(cin>>i);cin.clear();getchar();運行時如果輸入1 2 3 a時必須用getchar()才能在後面程序獲得正常輸入,即使先前已經恢復流了,此處用getch()是萬萬不行的。
程序例:
#include <stdio.h>
int main(void)
{
int c;
int a;
a = getch();
printf ("%c",a);
/* Note that getchar reads from stdin and
is line buffered; this means it will
not return until you press ENTER. */
while ((c = getchar()) != '/n')
{
printf("%c", c);
}
return 0;
}
注:可以利用getchar()函數讓程序調試運行結束後等待編程者按下鍵盤才返回編輯界面,用法:在主函數結尾,return 0;之前加上getchar();即可
putchar
函數名: putchar
功 能: 在stdout上輸出字符
用 法: int putchar(int ch);
程序例:
#include <stdio.h>
/* define some box-drawing characters */
#define LEFT_TOP 0xDA
#define RIGHT_TOP 0xBF
#define HORIZ 0xC4
#define VERT 0xB3
#define LEFT_BOT 0xC0
#define RIGHT_BOT 0xD9
int main(void)
{
char i, j;
/* draw the top of the box */
putchar(LEFT_TOP);
for (i=0; i<10; i++)
putchar(HORIZ);
putchar(RIGHT_TOP);
putchar('/n');
/* draw the middle */
for (i=0; i<4; i++)
putchar(VERT);
for (j=0; j<10; j++)
putchar(' ');
putchar(VERT);
putchar('/n');
/* draw the bottom */
putchar(LEFT_BOT);
for (i=0; i<10; i++)
putchar(HORIZ);
putchar(RIGHT_BOT);
putchar('/n');
return 0;
}
putchar函數(字符輸出函數)的作用是向終端輸出一個字符。其一般形式爲 putchar(c)
例:
#include<stdio.h>
void main()
{
char a,b,c;
a='T',b='M',c=‘D’;
putchar(a);putchar(b);putchar(c);putchar(/n);
putchar(a);putchar('/n');putchar(b);putchar('/n');putchar(c);putchar('/n');
}
輸出結果爲:
TMD
T
M
D