[英]How to output a character as an integer through cout?
#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+()
,該operator+()
僅通過值或通過引用對常量返回*this
。
將它們轉換為整數類型(並適當地使用位掩碼!)即:
#include <iostream>
using namespace std;
int main()
{
char c1 = 0xab;
signed char c2 = 0xcd;
unsigned char c3 = 0xef;
cout << hex;
cout << (static_cast<int>(c1) & 0xFF) << endl;
cout << (static_cast<int>(c2) & 0xFF) << endl;
cout << (static_cast<unsigned int>(c3) & 0xFF) << endl;
}
也許這個:
char c = 0xab;
std::cout << (int)c;
希望能幫助到你。
另一種方法是重載<<
運算符:
#include <iostream>
using namespace std;
typedef basic_ostream<char, char_traits<char>> basicOstream;
/*inline*/ basicOstream &operator<<(basicOstream &stream, char c) {
return stream.operator<<(+c);
}
/*inline*/ basicOstream &operator<<(basicOstream &stream, signed char c) {
return stream.operator<<(+c);
}
/*inline*/ basicOstream &operator<<(basicOstream &stream, unsigned char c) {
return stream.operator<<(+c);
}
int main() {
char var1 = 10;
signed char var2 = 11;
unsigned char var3 = 12;
cout << var1 << endl;
cout << var2 << endl;
cout << var3 << endl;
return 0;
}
打印以下輸出:
10
11
12
Process finished with exit code 0
我認為它非常整潔和有用。 希望它有幫助!
此外,如果您希望它打印一個hex
值,您可以這樣做:
basicOstream &operator<<(basicOstream &stream, char c) {
return stream.operator<<(hex).operator<<(c);
} // and so on...
除了cast (int)之外,另一種方法是使用std::hex :
std::cout << std::hex << (int)myVar << std::endl;
我希望它有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.