Why does printf( “%c”, 1) return smiley face instead of coded char for 1

霸气de小男生 提交于 2019-12-23 09:34:03

问题


This is my code

#include <stdio.h>

int x,y;

int main( void )
{
    for ( x = 0; x < 10; x++, printf( "\n" ) )
        for ( y = 0; y < 10; y++ )
            printf( "%c", 1 );

    return 0;
}

It returns smiley faces. I searched everywhere for a code for smiley face or a code for 1 but I didn't manage to find any links whatsoever or any explanation why char value for 1 returns smiley face, when the ascii code for 1 is SOH. I researched answers for this question but I didn't find any answers that explain why this happens.


回答1:


The output varies among different terminals. For example, on my OS X default terminal, no characters are output.

In your case, is output presumably due to some historical reasons. In short, this is because code page 437, which maps byte 0x01 to U+263A, is the character set of MS-DOS.




回答2:


Because 1 isn't a printable character code. If you want '1' you need to write it with the character literal:

 printf( "%c", '1' );
            // ^^^



回答3:


If you use a number, you'll select a character number from ASCII table, if you use a char you'll find the char.

Example: this code prints the ASCII character number 65:

printf( "%c", 65 ); // Outputs: A

This code prints the letter A:

printf( "%c", 'A' ); // Outputs: A


来源:https://stackoverflow.com/questions/37455047/why-does-printf-c-1-return-smiley-face-instead-of-coded-char-for-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!