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