在C ++中使用流操纵器解析std :: uint类型(Parse std::uint types using stream manipulators in C++)

编程入门 行业动态 更新时间:2024-10-27 08:38:02
在C ++中使用流操纵器解析std :: uint类型(Parse std::uint types using stream manipulators in C++)

我试图使用流操纵器解析文件。 但是,作为std::uint8_t的运算符>> overload,来自<istreams> std::uint16_t , std::uint32_t是格式化的输入函数,它会读取一个字符串,并在必要时将其转换为数字。 因此它将解析23到23而不是二进制表示00000010 00000011到515 。

您可以使用带有reinterpret_cast<>的inputstream.read()方法执行此操作:

is.read(reinterpret_cast<char*>(data), sizeof(*data));

现在我的问题 - 是否可以实现覆盖>>操作符的默认行为,以便我可以使用>>运算符读取这样的std:uint类型? 我该如何实现它,如何在运算符之间切换? 如果不可能,您是否知道实现流操纵器进行解析的好方法?

I am trying to parse a file using stream manipulators. However, as the operator>> overload for std::uint8_t, std::uint16_t, std::uint32_t from <istreams> is a formatted input function, it reads a string and if necessary converts it to a number. SO it would parse 23 to 23 and not the binary representation 00000010 00000011 to 515.

You can do this using the inputstream.read() method with a reinterpret_cast<>:

is.read(reinterpret_cast<char*>(data), sizeof(*data));

Now my question - Is it possible to implement to overwrite the default behavior of the >> operator so I can read in such std:uint types using the >> operator? How would I implement it and how can I switch between the operators? And if it is not possible do you know a nice way to implement a stream manipulator to do the parsing?

最满意答案

无法更改标准库提供的operator>>(std::istream&, uintN_t&)重载。

可以为自己的流类型添加operator>>(my_binary_stream&, uintN_t&)重载,并让它们执行二进制I / O. (您可以轻松地重新使用标准库流对象来支持您的自定义二进制流,例如使用.read()和.write()操作。)

It is not possible to change the operator>>(std::istream&, uintN_t&) overloads provided by the Standard Library.

You can add operator>>(my_binary_stream&, uintN_t&) overloads for your own stream type, and have them perform binary I/O. (You can easily re-use the Standard Library streams objects in support of your custom binary stream, e.g. using their .read() and .write() operations.)

更多推荐

本文发布于:2023-07-22 18:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   uint   std   Parse   manipulators

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!