c++ - 在 C++ 中将 unsetf 与十六进制十进制数和八进制数一起使用

标签 c++ c++11 c++14

我对使用 unsetf 有疑问.以下是为格式化数字获取正确输入的答案。

Actually, You can force operator>> to get and properly interpret prefixes 0 and 0x. All you have to do is to remove default settings for std::cin:

std::cin.unsetf(std::ios::dec);
std::cin.unsetf(std::ios::hex);
std::cin.unsetf(std::ios::oct);

Now, when you input 0x1a you will receive 26.

我不明白 hexoct 的最后两个 unsetf 命令。如果我仅将 unsetfdec 一起使用,我会得到正确的输入,我的意思是输入 0x1a 并接收 26

那么对hexdec使用unsetf有什么意义呢?

最佳答案

I don't understand the last two unsetf commands for hex and oct

如果 hexoct 标志之前没有设置,是的,取消设置 dec 就足够了:

std::cin.unsetf(std::ios::dec);
int n;
std::cin >> n;  // 0x1a
std::cout << n; // 26

( demo )

但是,如果之前设置了这些标志,它们可能会影响十六进制数的解析:

std::cin.unsetf(std::ios::dec);    
int n;
std::cin >> n;  // 0x1a
std::cout << n; // 0

( demo )

所以,如果你想让 std::cin 通过猜测它们的基数来解析你的数字,你应该 unsetf hex, dec oct

关于c++ - 在 C++ 中将 unsetf 与十六进制十进制数和八进制数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52180409/

相关文章:

c++ - 模板模拟上的 EXPECT_CALL

c++ - 使用模板对象的模板函数中无法识别的内容

c++ - 防止兄弟结构的平等比较

c++ - 指向成员函数的指针解析

c++ - 为什么 coliru 会为 chrono::system_clock::now().time_since_epoch() 返回相同的值?

c++ - 继承构造函数和大括号或等于初始值设定项

const && 的 C++11 绑定(bind)规则

c++ - 在 Ubuntu 16.04 下构建 Proxygen

c++ - 编程与原理第 6 章代币与计算器

c++ - C++中的空指针