了解包含反斜杠 (\012) 的 printf 输出

Understanding output of printf containing backslash (\012)

你能帮我理解这个简单代码的输出吗:

const char str[10] = "55234";
printf("%s", str);

输出为:

55
34

字符串中的字符序列 2 被解释为 octal escape sequence。解释为八进制的值 012 是十进制的 10,这是大多数终端上的换行符 (\n)。

来自维基百科页面:

An octal escape sequence consists of \ followed by one, two, or three octal digits. The octal escape sequence ends when it either contains three octal digits already, or the next character is not an octal digit.

由于您的序列包含三个有效的八进制数字,因此它将被解析。它不会继续使用 34 中的 3,因为那将是第四位数字并且仅支持三位数字。

所以你可以把你的字符串写成 "55\n34",这样你看到的更清楚,而且更便携,因为它不再对换行符进行硬编码,而是让编译器生成合适的东西.

2 是一个 escape sequence 表示 octal 符号代码:

012 = 10 = 0xa = LINE FEED (in ASCII)

所以你的字符串看起来像 55[LINE FEED]34

LINE FEED 字符在许多平台上被解释为 newline sequence。这就是您在终端上看到两个字符串的原因。

2 是一个新的行转义序列,正如其他人已经指出的那样。 (正如 chux 绝对正确评论的那样,如果 ASCII 不是使用的字符集,可能会有所不同。但无论如何它在这种表示法中是一个八进制数字。)

这是标准的意思,正如它在 ISO/IEC 9899

中对 c99 所说的那样

用于:

6.4.4.4 Character constants

[...]

3 The single-quote ', the double-quote ", the question-mark ?, the backslash \, and arbitrary integer values are representable according to the following table of escape sequences:

single quote' \'

double quote" \"

question mark? \?

backslash\ \

octal character \octal digits

hexadecimal character \x hexadecimal digits

它绑定的范围:

Constraints

9 The value of an octal or hexadecimal escape sequence shall be in the range of representable values for the type unsigned char for an integer character constant, or the unsigned type corresponding to wchar_t for a wide character constant.