开发者

Do I need to define ">>" operator to Use cin With Int32's?

开发者 https://www.devze.com 2023-01-14 01:25 出处:网络
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;

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::if开发者_开发问答stream 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/


The stream extraction operator (>>) performs formatted IO, not binary IO. You'll need to use std::istream::read instead. You'll also need to open the file as binary. Oh, and checking std::istream::eof is redundant in your code.

int32 my_int;
std::ifstream my_stream;

my_stream.open("my_file.txt",std::ios::in | std::ios::binary);
if (my_stream)
{
    my_stream.read(reinterpret_cast<char*>(&my_int), sizeof(my_int));
}
//Be sure to check my_stream to see if the read succeeded.

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 will be a typedef for whatever type happens to be a 32-bit signed integer on your platform. That underlying type will certainly have operator>> 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消