我需要定义“>>”吗?运算符将 cin 与 Int32 一起使用?
我需要从文件中准确读取 32 位。我在STL 中使用ifstream。我可以直接说:
int32 my_int;
std::ifstream my_stream;
my_stream.open("my_file.txt",std::ifstream::in);
if (my_stream && !my_stream.eof())
my_stream >> my_int;
...或者我是否需要以某种方式覆盖>>运算符与 int32 一起使用吗?我没有看到此处列出的 int32: http://www.cplusplus.com/reference/iostream/istream /运算符%3E%3E/
I need to read exactly 32 bits from a file. I'm using ifstream in the STL. Can I just directly say:
int32 my_int;
std::ifstream my_stream;
my_stream.open("my_file.txt",std::ifstream::in);
if (my_stream && !my_stream.eof())
my_stream >> my_int;
...or do I need to somehow override the >> operator to work with int32? I don't see the int32 listed here:
http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
流提取运算符 (
>>
) 执行格式化 IO,而不是二进制 IO。您需要使用std::istream::read
来代替。您还需要以二进制
形式打开该文件。哦,检查std::istream::eof
在您的代码中是多余的。请注意,这样做会引入对代码的平台依赖性,因为整数中的字节顺序在不同平台上是不同的。
The stream extraction operator (
>>
) performs formatted IO, not binary IO. You'll need to usestd::istream::read
instead. You'll also need to open the file asbinary
. Oh, and checkingstd::istream::eof
is redundant in your code.Note that doing this is going to introduce platform dependence on your code, because the order of bytes in an integer is different on different platforms.
int32
将是一个typedef
,适用于您平台上恰好是 32 位有符号整数的任何类型。该底层类型肯定会为其重载operator>>
。更新
正如 Billy 在下面指出的,流旨在读取文本并将其解析为重载数据类型。因此,在您的代码示例中,它将查找数字字符序列。因此,它不会从您的文件中读取 32 位。
int32
will be atypedef
for whatever type happens to be a 32-bit signed integer on your platform. That underlying type will certainly haveoperator>>
overloaded for it.Update
As Billy pointed out below, streams are designed to read text and parse it into the overloaded data type. So in your code example, it will be looking for a sequence of numeric characters. Therefore, it won't read 32 bits from your file.