複製鏈接
請複製以下鏈接發送給好友

putchar

鎖定
putchar,語法結構為 int putchar(int char) ,其功能是把參數 char 指定的字符(一個無符號字符)寫入到標準輸出 stdout 中,為C 庫函數 ,包含在C 標準庫中。其輸出可以是一個字符,可以是介於0~127之間的一個十進制整型數(包含0和127),也可以是用char定義好的一個字符型變量。 [1-2] 
中文名
單個字符輸出函數
外文名
putchar
格    式
int putchar(int char)
作    用
終端輸出一個字符
編程語言
C語言
變量類型
字符型(char)、整型(int)

putcharputchar語法

(1)函數聲明
int putchar(int char)
(2)參數
  • char-- 這是要被寫入的字符。該字符以其對應的 int 值進行傳遞。
(3)功能
把參數 char 指定的字符(一個無符號字符)寫入到標準輸出 stdout 中。 [3] 
(4)説明
該函數將指定的表達式的值所對應的字符輸出到標準輸出終端上。表達式可以是字符型或整型,它每次只能輸出一個字符。例如:“putchar('#')”輸出字符“#”。

putchar應用格式

putchar函數的基本格式為:putchar(c)。
(1)當c為一個被單引號(英文狀態下)引起來的字符時,輸出該字符(注:該字符也可為轉義字符);
(2)當c為一個介於0~127(包括0及127)之間的十進制整型數時,它會被視為對應字符的ASCII代碼,輸出該ASCII代碼對應的字符;
(3)當c為一個事先用char定義好的字符型變量時,輸出該變量所指向的字符。 [2] 

putchar注意事項

使用字符輸入/輸出函數時,必須在程序的前面加上頭文件#include <stdio.h>或#include "stdio.h"。並且,該函數的變量及輸出結果只能為一個字符。 [1] 

putchar函數返回值

該函數以無符號 char 強制轉換為 int 的形式返回寫入的字符。 [1] 
(1)當輸出正確的時候,返回輸出字符轉換為的unsigned int 值;
(2)當輸出錯誤的時候,返回 EOF(End of file)文件結束符
if(putchar(c)==EOF)
{
printf("output error:%m\n");
exit(0);
}

putchar程序示例

putchar示例1

#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示例2

#include <stdio.h>
int 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');
return 0;
}


輸出結果為:
TMD
T
M
D
參考資料
  • 1.    譚浩強 .C程序設計(第4版):清華大學出版社,2010.6
  • 2.    張權 .Objective-C函數速查實例手冊:人民郵電出版社,2014.2
  • 3.    尹德淳. C函數速查手冊:人民郵電出版社,2009.4