cout uint8_t as integers instead of chars(cout uint8_t 作为整数而不是字符)
问题描述
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
cout << (uint8_t)123 << endl;
}
这将输出 {
,因为 {
的 ASCII 是 123.
This will output {
, since {
's ASCII is 123.
但我想得到 123
代替.我发现 cout <<(int)123<
uint_8
转换为 int
.我可以配置 cout
来实现这一点吗?
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?
推荐答案
我绝对不会容忍我即将提出的解决方案.我也怀疑它可能不被标准所允许,但到目前为止我还不能证明这一点.如果有人可以向我提供表明不允许这样做的参考,那么我将删除此答案.无论如何,到目前为止,我的测试表明,在全局范围内简单地重载运算符似乎是可行的.
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;
}
我没想到这会起作用,但后来我意识到 operator<<
的 char/unsigned char/signed char
重载都是免费函数在 ADL 选取的 std
命名空间中.我想全局函数被认为比 ADL 函数更匹配,但我不确定这一点.
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.
这篇关于cout uint8_t 作为整数而不是字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:cout uint8_t 作为整数而不是字符
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01