Oliver Šmakal
Oliver Šmakal

Reputation: 83

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

Recently, I have used the >> operator when reading binary files, but in some cases it would just skip a byte. It caused me a lot of problems to find where the mistake is in my code, but finally I have managed to fix this with the get() method, but I still don't know why >> was skipping bytes from time to time.

The goal is to load the first byte from a file into m_Value, which is uint8_t.

Code with >>:

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

Code with get():

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

Upvotes: 0

Views: 397

Answers (1)

Lukas-T
Lukas-T

Reputation: 11340

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

The important difference is, formatted input will skip whitespace1 before extracting, and it will parse data. It's meant to extract text or numbers from a stream, not to read binary data.


1 unless explicitly configured otherwise, with std::noskipws

Upvotes: 5

Related Questions