cout uint8_t as integers instead of chars

2019-02-15 23:56发布

问题:

#include<algorithm>
#include<iostream>
using namespace std;

int main()
{
    cout << (uint8_t)123 << endl;
}

This will output { , since {'s ASCII is 123.

But I want to get 123 instead. I found cout << (int)123 << endl; will do this, but I'm not willing to cast uint_8 to int every times. Can I configure cout to achieve this?

回答1:

I definitely do not condone the solution I am about to suggest. I also suspect that it may not be permitted by the standard, but I cannot prove it, as of yet. If someone can provide me a reference that shows that it is not permitted, then I will delete this answer. Anyway, my tests so far indicate that simply overloading the operator in the global scope seems to work.

#include <iostream>
#include <cstdint>

std::ostream & operator<<(std::ostream & os, std::uint8_t val)
{
    return os << static_cast<int>(val);
}

int main()
{
    std::uint8_t val = 123;
    std::cout << val;
}

I wouldn't have thought this would work, but then I realized that the char/unsigned char/signed char overloads for operator<< are all free functions in the std namespace picked up by ADL. And I guess global functions are considered a better match than ADL functions, but I'm not sure about that.



标签: c++ stream