我需要界定“>>”操作符来将CIN用的Int32的?
-
26-09-2019 - |
题
我需要从文件中读取正好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 /
解决方案
在流提取运算符(>>
)进行格式化 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.
请注意,这样做是要在你的代码引进平台的依赖,因为字节的整数的顺序是在不同平台上的不同。
其他提示
int32
将是任何类型恰好是你的平台上的32位有符号整数typedef
。该底层类型肯定会operator>>
重载它。
<强>更新强>
如下面比利指出的,流被设计用于读取文本,并将其解析到重载的数据类型。因此,在你的代码示例,它会寻找的数字字符序列。因此,不会从文件中读出32位。
不隶属于 StackOverflow