在C语言中使用printf
时,如何转义百分号(%)?
printf("hello\%"); /* not like this */
在C语言中使用printf
时,如何转义百分号(%)?
printf("hello\%"); /* not like this */
你可以通过使用两个百分号 "%%" 来转义它,像这样:%%
以你的例子为例:
printf("hello%%");
转义百分号符号只适用于printf。 如果您执行以下操作:
char a[5];
strcpy(a, "%%");
printf("This is a's value: %s\n", a);
它将打印:This is a's value: %%
printf
,对吗? - Lazer\045
是编译时转义符,是语言的一部分,在编译后会变成 %
。printf
是一个运行时函数,因此它处理的是字符串的字节,而不是 C 源代码,并且它有自己的转义序列是函数的一部分。简而言之,printf
是“语言中的语言”,printf("This is a's value: %s\n", a);
和 printf("This is a's value: \045\0163\012", a);
会得到相同的结果。 - Triang3lprintf("hello%c", '%')
来实现这个功能。不过,最好使用%%
,因为它不需要使用另一个参数。 - Triang3l正如其他人所说,%%将会转义%符号。
然而,请注意,您永远不应该这样做:
char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);
每当你需要打印一个字符串时,一定要,一定要,一定要使用
printf("%s", c)
为了防止嵌入的百分号引起问题(如内存违规,分段错误等),需要进行转义。
fputs(string, stdout);
或者printf("%s", string);
。 - Jonas Kölkerputs
。我从来没有想过用puts
打印字符串,直接跳到了printf
。不再这样了。 - Lazer通过自身...
printf("hello%%"); /* like this */
小问题:
在指定 printf()
(和scanf()
)函数格式的字符串中,您实际上没有转义 %
。
%
在 printf()
(和scanf()
)函数中开始一个转换规范。 转换规范的规则之一是,将 %
作为转换说明符(紧随开始转换规范的 %
)会导致写入一个带有未转换参数的 '%'
字符。
该字符串实际上有2个'%'
字符(与转义字符不同:"a\bc"
是一个具有3个非空字符的字符串; "a%%b"
是一个具有4个非空字符的字符串)。
像这样:
printf("hello%%");
//-----------^^ inside printf, use two percent signs together
您可以使用%%:
printf("100%%");
结果是:
100%
%
识别为特殊字符,因此不需要进行转义。但是在使用printf
函数时,需要使用%%
来打印一个%
符号。
"hello\%"
无法正常工作,因为它会像"hello%"
一样生成字符串hello%
加上NUL。 - ikegami"hello\%"
doesn't work because... for me... it does not compile. I used Microsoft Visual Studio 2017. The compilation fails with the message:'%': unrecognized character escape sequence.
- Djibril NDIAYE\%
。 - Ruud Helderman