c++ - 如何通过cout将字符输出为整数?

标签 c++ io type-conversion iostream outputstream

#include <iostream>

using namespace std;

int main()
{  
    char          c1 = 0xab;
    signed char   c2 = 0xcd;
    unsigned char c3 = 0xef;

    cout << hex;
    cout << c1 << endl;
    cout << c2 << endl;
    cout << c3 << endl;
}

我预计输出如下:

ab
cd
ef

然而,我什么也没得到。

我猜这是因为 cout 总是将 'char'、'signed char' 和 'unsigned char' 视为字符而不是 8 位整数。但是,“char”、“signed char”和“unsigned char”都是整数类型。

所以我的问题是:如何通过 cout 将字符输出为整数?

PS:static_cast(...) 很难看,需要更多的工作来修剪额外的位。

最佳答案

char a = 0xab;
cout << +a; // promotes a to a type printable as a number, regardless of type.

只要该类型提供具有普通语义的一元 + 运算符,这将起作用。如果您要定义一个表示数字的类,要提供具有规范语义的一元 + 运算符,请创建一个 operator+() 来简单地按值或按返回 *this对常量的引用。

来源:Parashift.com - How can I print a char as a number? How can I print a char* so the output shows the pointer's numeric value?

关于c++ - 如何通过cout将字符输出为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14644716/

相关文章:

c++ - CGAL 的 istream_iterator

io - 内存映射 IO 与 DMA?

python - 客户端-服务器 python 将字节转换为字符串

c++ - 在 VS2010 C++ 中从 'double' 转换为 'int'

C++空间问题

c++ - 如何使用静态删除器创建 unique_ptr

c++ - 快速序列有序 Walsh-Hadamard 变换

java - ObjectInputStream.GetField 和 ObjectOutputStream.PutField

c++ - 类运算符重载

prolog - 在 Prolog 中将字符列表转换为字符串