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

What is the difference between ifstream operator>> and get() method?

最近,我在读取二进制文件时使用了>>运算符,但在某些情况下它只会跳过一个字节。这让我很难找到代码中的错误位置,但最后我设法用 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;
}

operator>>formatted input function and get() is an unformatted input function.

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


1 除非另外明确配置,std::noskipws