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;
}
根据这个链接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
,也将读取空白,并失败。
相关文章:
- 为什么istream不支持右值提取
- 将无符号char*转换为std::istream*C++
- 需要从 istream 和 ostream 派生 iostream
- 使用std::istream::peek()总是安全的吗
- EASTL矢量<向量<int>>连续的
- 使用 istream 参数读取的 istream 函数
- istream std::cin如何修改自定义istream缓冲区
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 在清除 istream 之前,我不应该需要取消获取它吗?
- C++,如何根据运行时条件构造引用不同 istream 对象的对象?
- 如何将QByteArray转换为std::istream或std::ifstream?
- 逗号在重载 ostream 和 istream 在结构中分开
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- 从函数返回 istream 的正确方法
- 阅读从 istream 到矢量的不同类型列表
- 关于 istream 中的错误处理的问题
- C++ 模板类无法修复 ostream 和 istream 函数
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- iStream 运算符跳过空格字符
- 如何在 c++ 中将 IStream 转换为 Base64 字符串