istream::operator>> 或 istream::get

istream::operator>> or istream::get

我正在测试 C++PL 书中的一段代码并找到了下一段代码(我不想感觉我是在将它从书中复制粘贴到我的 IDE 所以我至少更改了变量名称):

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;
}

根据this link istream::get "Extracts a single character from the stream"

并根据this link istream::operator>> "Extracts as many characters as possible from the stream"

出于好奇,我替换了

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

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

它奏效了。没有编译错误,程序显然做了它应该做的,现在我的问题是:

为什么在我们提取单个字符的上下文中使用运算符 >>,而 is.get() 具有同等功能?

operator >>get() 之间的主要区别是前者跳过前导空格,而后者则不会。

您的变体 "worked",但对输入有更严格的要求。

原代码会成功读取{ "John Doe" , 29 },但如果使用get也会读取空白,并失败。