在编写自己的流运算符时,如何检查当前的 ostream dec/hex 模式?
How can I check the current ostream dec/hex mode when writing my own streaming operator?
我正在编写一个简单的类,它有一个朋友来写入输出流,例如std::cout
。
我的类的状态可以用数字形式表示,我可能希望看到十进制或十六进制。
如果我正在打印一个 PODint
,我可以使用std::hex
修饰符;我想做的是在我的函数中检查它并采取相应的行动。 到目前为止,我的搜索是空白的。
class Example
{
friend std::ostream& operator<<( std::ostream& o, const Example& e );
};
std::ostream& operator<<( std::ostream& o, const Example& e )
{
if ( /*check for hex mode*/ )
o << "hexadecimal";
else
o << "decimal";
return o;
}
我应该用什么来代替/*check for hex mode*/
?
编辑:我使我的例子超级通用。
您可以使用ostream
的flags()
函数,查看是否设置了hex
位:
bool isHexMode(std::ostream& os) {
return (os.flags() & std::ios_base::hex) != 0;
}
回答我自己的问题,感谢@AProgrammer为我指出正确的方向。
std::ostream& operator<<( std::ostream& o, const Example& e )
{
if ( o.flags() & std::ios_base::hex ) // <-----
o << "hexadecimal";
else
o << "not hexadecimal";
return o;
}
相关文章:
- ostream过载时的缓冲区冲洗
- 需要从 istream 和 ostream 派生 iostream
- "ostream &os"有什么用?
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++表达SFINAE和ostream操纵器
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 逗号在重载 ostream 和 istream 在结构中分开
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- ostream 运算符<< 为获取 STL 容器而过载,传递 std::string 会破坏它?
- 将 ostream 包装在类中并模板化<<运算符
- 如何在C++中编写 ostream 的向量,它接收所有不同的输出流,如 cout、ostringstream 和 ofs
- 将十六进制转换为 DEC
- 为什么在返回 ostream 类时使用引用?
- 将标准输出重定向到ostream
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 无法从好友功能访问类的私有成员?"ostream"不是"std"的成员?
- 在编写自己的流运算符时,如何检查当前的 ostream dec/hex 模式?