istream::operator>> 或 istream::get

istream::operator>> or istream::get

本文关键字:gt istream get operator      更新时间:2023-10-16

我正在测试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;
}

根据这个链接istream::get"从流中提取单个字符"

根据此链接istream::operator>>"从流中提取尽可能多的字符"

出于好奇,我更换了

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

带有

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

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

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

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

您的变体"有效",但对输入提出了更严格的要求。

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