我需要定义“>>”吗?运算符将 cin 与 Int32 一起使用?

发布于 2024-09-17 12:39:08 字数 478 浏览 3 评论 0原文

我需要从文件中准确读取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋意浓 2024-09-24 12:39:08

流提取运算符 (>>) 执行格式化 IO,而不是二进制 IO。您需要使用 std::istream::read 来代替。您还需要以二进制形式打开该文件。哦,检查 std::istream::eof 在您的代码中是多余的。

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.

请注意,这样做会引入对代码的平台依赖性,因为整数中的字节顺序在不同平台上是不同的。

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.

很酷又爱笑 2024-09-24 12:39:08

int32 将是一个 typedef,适用于您平台上恰好是 32 位有符号整数的任何类型。该底层类型肯定会为其重载operator>>

更新

正如 Billy 在下面指出的,流旨在读取文本并将其解析为重载数据类型。因此,在您的代码示例中,它将查找数字字符序列。因此,它不会从您的文件中读取 32 位。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文