目录

putchar和printf的区别

putchar和printf的区别是:1. 从编程者层面来说;2. 从底层来说。其中,printf 可以输出一个任意的字符串,还可以有参数,而putchar只能输出一个字符。printf 的返回值是正常输出的参数的数量,而 putchar 则是是否正常输出。

一、putchar和printf的区别

1. 从编程者层面来说

printf 可以输出一个任意的字符串,还可以有参数,而putchar只能输出一个字符。

printf 的返回值是正常输出的参数的数量,而 putchar 则是是否正常输出。

putchar:是把参数 char 指定的字符(一个无符号字符)写入到标准输出 stdout 中。

printf:是式样化输出函数, 用于向准则输出设备按规定式样输出消息。

输出方式不同

putchar:输出可以是一个字符,可以是介于0~127之间的一个十进制整型数(包含0和127),也可以是用char定义好的一个字符型变量。

printf:从右到左压栈,然后将先读取放到栈底,最后读取的放在栈顶,处理时候是从栈顶开始的。

putchar:该函数以无符号 char 强制转换为 int 的形式返回写入的字符。

printf:函数返回值为整型。若成功则返回输出的字符数,输出出错则返回负值。

2. 从底层来说

printf 的时间复杂度是 NlogN , 而 putchar 复杂度是 O1 , 输出句子也只有 ON 。

此外,printf 每执行一次,解析一次格式串,而putchar是编译时尽量优化。

简言之:printf功能更强大 可以输出各种格式。putchar只能输出单个字符。因为字符的处理很特殊,所以专门有对字符的处理,如 putchar ,getchar 之类的。

延伸阅读:

二、putchar程序示例

示例1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #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 较好 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; } }

示例2

1 2 3 4 5 6 7 8 9 10 11 #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; }
1 2 3 4 5 输出结果为: TMD T M D
一站式研发项目管理平台 PingCode

一站式研发项目管理平台 PingCode

支持敏捷\瀑布、知识库、迭代计划&跟踪、需求、缺陷、测试管理,同时满足非研发团队的流程规划、项目管理和在线办公需要。