[英]How does the language differentiate from format code like %s and actual string "%s"?
For example, in the code printf("hello world, %s", variable) it would print "hello world stack", but what if I actually wanted to print "hello world %s"?例如,在代码 printf("hello world, %s", variable) 中,它会打印“hello world stack”,但如果我真的想打印“hello world %s”呢?
How does the computer/language know the difference?计算机/语言如何知道差异? From my perspective, it seems like the format code (%s) is left inside the quotes, therefore it should print the whole thing as a string.从我的角度来看,格式代码 (%s) 似乎保留在引号内,因此它应该将整个内容打印为字符串。
You are right about the string part - a format string is just any ordinary string, and the '%'
is stored in the memory just as a percentage sign.您对字符串部分是正确的 - 格式字符串只是任何普通字符串,并且'%'
作为百分号存储在 memory 中。 In fact, if you feed the very same string to puts
, it just prints %s
as is.实际上,如果您将相同的字符串提供给puts
,它只会按原样打印%s
。
However, the interpretation of the format string of printf
-family functions is done at runtime: it actually scans the format string character by character, and whenever it encounters a '%'
, it parses the neighbouring few char
s as a format specifier, and formats the corresponding parameter.但是, printf
系列函数的格式字符串的解释是在运行时完成的:它实际上是逐个字符地扫描格式字符串,并且每当遇到'%'
时,它都会将相邻的几个char
解析为格式说明符,并且格式化相应的参数。
To print a literal '%'
however, you just use %%
and printf
will know to output a percentage sign.但是,要打印文字'%'
,只需使用%%
, printf
就会知道 output 是一个百分号。
You can read the glibc implementation of printf
-family functions here .您可以在此处阅读printf
系列函数的 glibc 实现。 Or a much tidier musl implementation of strftime
here .或者这里是strftime
的更整洁的 musl 实现。
You can escape the '%' character with another '%':您可以使用另一个 '%' 转义 '%' 字符:
printf("Hello: %%s\r\n");
will print "Hello: %s "将打印“你好:%s”
You can use printf("%%s")
to print "%s", but you should really only use the pattern string for patterns.您可以使用printf("%%s")
打印“%s”,但实际上您应该只使用模式字符串作为模式。 It would be better to do something like printf("%s", "%s")
- that is, the string you want to print is the second, it will not interpret "%s", "%d", or any other pattern so you don't have to worry about how to express them.最好执行printf("%s", "%s")
之类的操作 - 也就是说,您要打印的字符串是第二个,它不会解释 "%s"、"%d" 或任何其他模式,因此您不必担心如何表达它们。
It's also kind of useless and confusing for a single string, so better to use puts("%s")
.对于单个字符串来说,这也有点无用和混乱,所以最好使用puts("%s")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.