gpt4 book ai didi

c++ - istream::operator>> 或 istream::get

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:00 25 4
gpt4 key购买 nike

我正在测试 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 "从流中提取单个字符"

并根据this link istream::operator>> "从流中提取尽可能多的字符"

出于好奇,我更换了

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

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

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

为什么运算符是>>在我们提取单个字符的上下文中使用,当 is.get()功能一样吗?

最佳答案

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

关于c++ - istream::operator>> 或 istream::get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com