为什么要先理解和学好这个函数呢?因为,我们后面学习C,很多时候都需要用到这个函数,这个函数是用来输出内容到控制台上面的。
1 printf函数
我们前面的例子就用到了它
// 调用printf输出字符串,\n代表换行
printf("hello, world\n");
Code language: C/AL (cal)
printf() 标准打印库函数
printf("内容") 就是给它传一个字符串参数;把双引号内的字符输出到控制台;
语句结尾必须加分号 ;,代表一条语句结束,漏写分号会编译报错。看如下输出错误信息:
C:\cdemo>gcc hello.c -o hello.exe
hello.c: In function 'main':
hello.c:5:29: error: expected ';' before 'return'
printf("hello, world\n")
^
;
return 0;
~~~~~~Code language: PHP (php)
如果我们要输出多行文本。可以这样:
#include <stdio.h>
main()
{
printf("第一行文字\n");
printf("第二行文字\n");
}Code language: PHP (php)
2 字符串
被英文下的双引号 " " 包裹的一串字符,如 "hello, world\n"
我们前面的例子,字符串都是作为printf的参数,用来直接把这个字符串输出到控制台中
字符串不能换行拆分书写,下面代码会直接编译报错:
// 错误示范:字符串拆分成两行
printf("hello, world
");
Code language: C/AL (cal)
编译错误返回
C:\cdemo>gcc hello.c -o hello.exe
hello.c: In function 'main':
hello.c:6:11: warning: missing terminating " character
printf("hello, world
^
hello.c:6:11: error: missing terminating " character
printf("hello, world
^~~~~~~~~~~~~
hello.c:7:4: warning: missing terminating " character
");
^
hello.c:7:4: error: missing terminating " character
");
^~~
hello.c:8:5: error: expected expression before 'return'
return 0;
^~~~~~
hello.c:8:14: error: expected ';' before '}' token
return 0;
^
;
}
~Code language: PHP (php)
3 转义字符 \n 换行符
\n 是 C 语言专用标记,代表换行字符;
printf 不会自动换行,必须手动加\n才能让光标跳到下一行;
如果没有\n 那么就会显示到一行里面,看下面例子
#include <stdio.h>
int main()
{
// 不带\n:两行文字挤在同一行输出
printf("hello");
printf("world");
// 带\n:输出后自动换行
printf("\nhello\n");
printf("world\n");
return 0;
}Code language: PHP (php)
C:\cdemo>gcc hello.c -o hello.exe
C:\cdemo>hello
helloworld
hello
world
C:\cdemo>Code language: CSS (css)
hello 和world 在一行里面贴着输出了。所以,如果读者要使用printf输出内容,如果要换行,记得加上\n,一个\n相当于敲回车键一次,如果连续输出两个\n 则等于输出两次换行,这时候两个字符串之间就会有一个空行了,和你再记事本中敲两次回车键一样。
#include <stdio.h>
int main()
{
printf("one\n\n");
printf("two");
return 0;
}Code language: PHP (php)
执行结果
C:\cdemo>gcc hello.c -o hello.exe
C:\cdemo>hello
one
two
C:\cdemo>Code language: CSS (css)
多段拼接输出,分多次 printf 拼成一行
看例子
#include <stdio.h>
int main()
{
printf("hello, ");
printf("world");
printf("\n"); // 最后统一换行
}Code language: PHP (php)

易错点补充
#include <stdio.h>
以上的,预处理引入头文件,末尾没有分号;
要使用printf函数,需要引入#include <stdio.h> 否则会报错
Previous: 讲解第一个C程序