Zero Lee的专栏

输出字符'A'/'a'的解析

输出字符'A'/'a'的代码段:
 1     // Test1: Directly insert 0x0A and 0x41 to ostream
 2    cout << 0x0A;    // print type int 10
 3
 4    cout << ' ';
 5
 6    cout << 0x41;    // print type int 65, which is decimal number of 'A'.
 7    cout << ' ';
 8
 9    // Test2: Directly insert '\x41' to ostream
10    cout << '\x41';    // '\x41' is transformed char, which means type char 'A'.
11                       // So, it prints type char 'A'  on screen.
12    cout << ' ';
13
14    // Test3: First assign 0x41 to char variable, then output it.
15    char char_out = 0x41;    // char_out is equal 'A' which is type int 65.
16    cout << char_out;        // it prints type char 'A' on screen.
17
18    cout << ' ';
19    // Test4: First cast 0x0A to char, then output it.
20    cout << static_cast<char>(0x41); // it prints type char 'A' on screen.
21    
22    cout << ' ';

23    // Test5: Directly insert hexdecimal type number of 'A'
24     cout << std::hex /*<< std::showbase*/ << 0x41// it prints string literal "41" 
25    cout << ' ' << std::hex << 0x0A// it prints type char 'a' on screen.
26    int int_out = '0x41';
27    cout << int_out; // it prints type int 8342**
28
29    cout << endl;
   0x41是字符'A'的16进制表示方式,它的10进制数是65,\x41是字符'A'的转义字符。而0x0A跟字符'A'没有丝毫关系,顶多就是0x0A借用了字符'A'而已。故如果想在屏幕上输出字符'A'可将其转义字符直接插入输出流中,或者将0x41转化为字符类型,然后插入,不得使用0x41直接插入,因为0x41本身是int类型的10进制数65。同时也不可以将'0x41'直接插入输出流,因为'0x41'是int类型的数。
   可以尝试使用控制符std::hex来插入字符'a'到输出流。

posted on 2007-01-15 10:59 Zero Lee 阅读(966) 评论(0)  编辑 收藏 引用 所属分类: C++ Performance


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理