简体   繁体   English

为什么`printf(“%c”,5)`打印竖线?

[英]Why does `printf(“%c”, 5)` print a vertical bar?

Here is the code 这是代码

#include <stdio.h>

int main()
{
    printf ("\t%d\n",printf("MILAN"));
    printf ("\t%c",printf("MILAN"));
}

Here is the output 这是输出

$gcc -o main *.c
$main

MILAN 5 米兰5

MILAN | 米兰|

Now the question is 现在的问题是

Why printf return | 为什么printf返回| when we are printing characters (formatter as %c) ? 当我们打印字符时(格式为%c)?

What is the relation between 5 and | 5和|之间的关系是什么? here? 这里?

Your question really boils down to the behaviour of printf("%c", 5); 您的问题实际上归结为printf("%c", 5);的行为printf("%c", 5); .

The actual output is a function of the character encoding used by your platform. 实际输出取决于平台使用的字符编码 If it's ASCII (very common) then it will output the control character ENQ . 如果是ASCII(非常常见),则将输出控制字符 ENQ What you actually get as an output will depend on your command shell, and a vertical bar is not an unreasonable choice. 您实际获得的输出将取决于命令外壳,竖线也不是不合理的选择。

printf returns the number of characters printed . printf返回打印的字符数 In this case, that number is 5, as you've seen. 如您所见,在这种情况下,该数字为5。 The second print you're doing tries to typecast that int to a char , which C lets you do because it's C. On your computer, it shows up as a |. 您正在执行的第二个打印尝试将int转换为char ,因为C是C,所以C可以让您这样做。在计算机上,它显示为|。 I see it rendered as a blank character. 我看到它呈现为空白字符。 As @Bathsheba says, the integer 5 corresponds to a control character in ASCII, and the rendering for those is system-dependent. 正如@Bathsheba所说,整数5对应于ASCII中的控制字符,并且这些字符的呈现方式与系统有关。

Here's an ascii table, if you're curious about other numbers . 如果您对其他数字感到好奇,这是一张ascii表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM