假设我们要在屏幕上打印 c:\test\test.c
#include <stdio.h>
int main()
{
printf("c:\test\test.c");
return 0;
}
但是打印出来的结果,却不符合我们的预期。
这便是转义字符的原因,转义字符就是转变了其本来的意思。
C语言中的转义字符
转义字符 | 释义 |
---|---|
\? | 连续书写多个问号时使用,防止他们被解析成三字母词 |
\' | 用于表示字符常量 ' |
\" | 用于表示一个字符串内部的双引号 " |
\\ | 用于表示一个反斜杠,防止它被解释为一个转移序列符 |
\a | 警告字符,蜂鸣 |
\b | 退格符 |
\f | 进纸符 |
\n | 换行 |
\r | 回车 |
\t | 水平制表符 |
\v | 垂直制表符 |
\ddd | ddd表示1~3个八进制数字,如:\130 打印出 X |
\xdd | dd表示2个十六进制数字,如:\x30 打印出 0 |
转义字符 \?
早期C语言中,如果要打印 ( are you ok ??) 但是后面的 ??) 会被识别成一个三字母词 ]
#include <stdio.h>
int main()
{
printf("(are you ok ??)");
return 0;
}
无法正确的打印出来,此时则需要转义字符 \?
#include <stdio.h>
int main()
{
printf("( are you ok \?\?)");
return 0;
}
对两个连续的 ?? 进行转义,防止它们被解析成一个三字母词 ]
转义字符 \'
当我们想打印一个单引号 ' 时,如果不适用转义字符,会因为单引号的配对问题报错
#include <stdio.h>
int main()
{
printf("%c\n",'''); //!带引号的字符串应至少包含一个字符
return 0;
}
这是因为每两个单引号会被识别成一对,这样就会有一个单引号是单独的。
#include <stdio.h>
int main()
{
printf("%c\n",'\'');
return 0;
}
使用转义字符 \' 后,则说明这就是一个字符 ' 而已。
转义字符 \"
原理同上
#include <stdio.h>
int main()
{
printf("%s\n",""");//!缺少右引号
return 0;
}
使用转义字符后
#include <stdio.h>
int main()
{
printf("%s\n","\"");
return 0;
}
转义字符 \\
开头我们尝试打印 c:\test\test.c 却没有成功,是因为 \t 被识别成了转移字符 \t (水平制表符,相当于键盘上的 Tab 键)
则我们使用转义字符 \\ 使 \t 中的 \ 转义成普通的 \ 并不是转义字符 \t 中的 \
#include <stdio.h>
int main()
{
printf("c:\\test\\test.c");
return 0;
}
转义字符 \a
触发电脑的蜂鸣
#include <stdio.h>
int main()
{
printf("\a\a\a");
return 0;
}
电脑会有三声蜂鸣
转义字符 \ddd
ddd表示1~3个八进制数字
如:\130 打印出 X
#include <stdio.h>
int main()
{
printf("%c\n",'\130');
return 0;
}
为什么会打印出大写的 X 呢?
而八进制的 130 转换成十进制是多少呢?
我们已知
1 3 0
10^2 10^1 10^0
1*10^2+3*10^1+0*10^0 = 130
则
1 3 0
8^2 8^1 8^0
1*8^2+3*8^1+0*8^0 = 64+24+0=88
查阅 ASCII码表 可知十进制 88 代表 大写 X
倘若我们想打印 大写A
查阅 ASCII码表 我们知道 A 的 ASCII码值为 65
十进制 65 转为八进制为 101
#include <stdio.h>
int main()
{
printf("%c\n",'\101');
return 0;
}
在 ASCII码表 中,每一个字符都有一个 ASCII码值。
转义字符 \xdd
dd表示2个十六进制数字
如:\x30 打印出 0
#include <stdio.h>
int main()
{
printf("%c\n",'\x30');
return 0;
}
原理同上
转义字符测试题:
下面代码的执行结果是多少?
#include <stdio.h>
int main()
{
printf("%d\n",strlen("c:\test\328\test.c"));
return 0;
}
c:\test\328\test.c
c : \t e s t \32 8 \t e s t . c
1 2 3 4 5 6 7 8 9 10 11 12 13 14
所以结果为 14