Compa
Compa

Reputation: 190

istream::operator>> or istream::get

I was testing a block of code from the C++PL book and found the next piece of code (I didn't want to feel like I was copypasting it from the book to my IDE so I , at least, changed the variable names):

istream& operator>> (istream& is, MyContact& mc)
{
    char ch1, ch2;
    string ContactName{""};
    if (is>>ch1 && is>>ch2 && ch1=='{' && ch2=='"')
    {
        while(is>>ch1 && ch1 != '"')
            ContactName+=ch1;

        if (is>>ch1 && ch1==',')
        {
            int ContactAge=0;
            if (is>>ContactAge>>ch1 && ch1=='}')
            {
                mc={ContactName, ContactAge};        
                return is;
            }
        }
    }

    is.setstate(ios_base::failbit);
    return is;
}

According to this link istream::get "Extracts a single character from the stream"

And according to this link istream::operator>> "Extracts as many characters as possible from the stream"

Out of curiosity, I replaced

if (is>>ch1 && is>>ch2 && ch1=='{' && ch2=='"')

with

if (is.get(ch1) && is.get(ch2) && ch1=='{' && ch2=='"')

And it worked. No compilation errors and the program apparently did what it was supposed to do, now my question is:

Why is the operator >> used in the context where we extract a single char, when an is.get() would be equally functional?

Upvotes: 0

Views: 134

Answers (2)

molbdnilo
molbdnilo

Reputation: 66441

Your variant "worked", but imposes stricter requirements on the input.

The original code will succesfully read { "John Doe" , 29 }, but if you use get you will also read the whitespace, and fail.

Upvotes: 1

Quentin
Quentin

Reputation: 63144

The main difference between operator >> and get() is that the former skips leading whitespace, while the latter doesn't.

Upvotes: 4

Related Questions