ifstream operator >>和get()方法有什么区别?

时间:2020-03-18 07:53:12

标签: c++ fstream binaryfiles ifstream

最近,我在读取二进制文件时使用了>>运算符,但是在某些情况下,它只会跳过一个字节。这导致我发现代码错误所在的地方很多问题,但最终我设法用get()方法解决了这个问题,但是我仍然不知道为什么>>跳过字节不时。

目标是将文件中的第一个字节加载到m_Value中的uint8_t中。

带有>>的代码:

bool CByte :: load ( ifstream & fin)
{
    if(! ( fin >> m_Value ) ) return false;
    return true;
} 

带有get()的代码:

bool CByte :: load ( ifstream & fin)
{
    char c = 0;
    if(! ( fin . get ( c ) ) ) return false;
    m_Value = static_cast <uint8_t> (c);
    return true;
}

1 个答案:

答案 0 :(得分:4)

operator>>formatted input function,而get()unformatted input function

重要的区别是,格式化的输入将在提取之前跳过空格 1 ,并且会进行解析数据。它旨在从流中提取文本或数字,而不是读取二进制数据。


除非另有明确配置,否则

1 使用std::noskipws

相关问题