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?
Aucun commentaire:
Enregistrer un commentaire