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?
operator >>
和get()
之间的主要区别在于,前者跳过前导空格,而后者没有。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.