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/60985861/

相关文章:

C++调用父类(super class)

java - 有没有办法在Android(外部存储)上的我的文件中创建一个文件夹并将文件写入该文件夹?

c++ - 为什么这个 double 到 int 的转换不起作用?

java - Scala 和 Java 数据结构

c++ - 推力排序示例中的崩溃

c++ - 使用 QQuickView 或 QQmlApplicationEngine 在 ApplicationWindow 之间切换页面

c++ - 为什么在重建工作时构建后源代码的更改并不总是反射(reflect)在机器代码中?

java - 关于通过ByteBuffer写入Char的查询

c# - 如何检查文件当前是否打开或正在写入 .NET?

c - C 中的隐式数据类型转换