【问题标题】:What is the difference between ifstream operator>> and get() method?ifstream operator>> 和 get() 方法有什么区别?
【发布时间】:2020-03-18 07:53:12
【问题描述】:

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

【问题讨论】:

  • 格式化提取运算符&gt;&gt; 用于读取文本。它不适用于任意二进制数据。

标签: c++ fstream binaryfiles ifstream


【解决方案1】:

operator&gt;&gt;formatted input functionget()unformatted input function

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


1 除非另有明确配置,否则使用std::noskipws

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2021-04-16
    • 2016-09-07
    • 2013-08-26
    • 1970-01-01
    • 2018-05-30
    • 2013-01-19
    • 1970-01-01
    相关资源
    最近更新 更多