c++ - 我是否需要定义 ">>"运算符才能将 cin 与 Int32 一起使用?

标签 c++ file-io operator-overloading ifstream

我需要从文件中准确读取 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/operator%3E%3E/

最佳答案

流提取运算符 (>>>) 执行格式化 IO,而不是二进制 IO。您需要改用 std::istream::read。您还需要将文件作为 binary 打开。哦,检查 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.

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

关于c++ - 我是否需要定义 ">>"运算符才能将 cin 与 Int32 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631655/

相关文章:

php - 在 PHP 中解析 ini 文件是否比在代码中定义变量更好?

c - 二进制文件读取,在c中添加额外的字符?

python:根据种类对每个条目进行编号

c++ - 重载运算符 delete 可以有默认参数吗?

c++ - 没有内存拷贝的运算符重载

c++ - 指针是否有可能在没有任何数据拷贝的情况下由 vector 拥有?

c++ - 如何使用 put_time() 格式化日期以删除前面的空格和零?

c++ - 增量构建 : Eclipse CDT does not notice that source has changed

c++ - 如何以 boost spirit 允许好的空间并禁止坏的空间

c++ - 如何创建一个只能添加一次的类?