忽略这个问题。错误询问:
以下 2 个 printf 语句之间有什么区别:
printf($variable, "\n");
printf("Hello\n");
Run Code Online (Sandbox Code Playgroud)
换行符在第一个 printf() 语句中被忽略。但它适用于第二个语句。
我可以使用新行的唯一方法是将第一个语句分成 2 个单独的语句:
printf($variable);
printf("\n");
Run Code Online (Sandbox Code Playgroud)
这听起来像是来自一个绝对新手的查询,但是我觉得换行在 Java 中得到了很好的支持,但在 PHP 中却没有。
正如官方文档中所写:
有两个字符串运算符。第一个是连接运算符 ('
.'),它返回其左右参数的连接。
PHP 中的正确语法是:
printf($variable . "\n");
Run Code Online (Sandbox Code Playgroud)
\n被忽略,因为如文档中所述,第一个参数是format应该打印的参数,其余参数是此格式可以使用的值,例如:
$num = 2.12;
printf("formatted value = %.1f", $num);
// ^^^^^^^^^^^^^^^^^^^^^^ ^^^^
// | |
// format |
// value which can be put in format in place of `%X` where `X` represents type
Run Code Online (Sandbox Code Playgroud)
将打印,formatted value = 2.1因为在格式中%.1f您决定仅打印浮点数中点后的一位数字。
要使格式使用字符串参数,您需要使用%s占位符,例如在print("hello %s world","beautiful")这种情况下将代替beautiful和%sprint hello beautiful world。
现在让我们回到你的代码。Inprintf($variable, "\n"); $variable表示格式,并且它很可能没有any %sfor 字符串,这可以让您"\n"以这种格式放置 use 参数。这意味着"\n"将被忽略(不在格式中使用),因此不会被打印。
像这样的代码
printf("Hello\n");
Run Code Online (Sandbox Code Playgroud)
或者
printf($variable);
printf("\n");
Run Code Online (Sandbox Code Playgroud)
没有这个问题,因为它明确使用\n应该打印的格式。
所以看来你可能想使用
printf("%s\n", $value)
Run Code Online (Sandbox Code Playgroud)
这看起来有点矫枉过正,因为您可以简单地使用.运算符连接字符串并像这样打印它们
print($value."\n")
Run Code Online (Sandbox Code Playgroud)
或者
echo $value."\n";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14264 次 |
| 最近记录: |