Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

c++ - cout uint8_t as integers instead of chars

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...