【问题标题】:How can I read from an std::istream (using operator>>)?如何从 std::istream 中读取(使用运算符>>)?
【发布时间】:2010-11-21 03:19:35
【问题描述】:

如何使用operator>>std::istream 中读取信息?

我尝试了以下方法:

void foo(const std::istream& in) {
  std::string tmp;
  while(in >> tmp) {
     std::cout << tmp;
  }
}

但它给出了一个错误:

error: no match for 'operator>>' in 'in >> tmp'

【问题讨论】:

  • istream 一开始不应该是 const。由于您从中提取数据,istream 对象的状态将需要更改。

标签: c++ operators istream extraction-operator


【解决方案1】:

你这样做是对的。你确定你包含了所有你需要的标题吗? (&lt;string&gt;&lt;iostream&gt;)?

【讨论】:

  • 是的,包括
  • 尤金是对的。我没有注意到 const 引用。它抱怨这个特定错误的原因是因为没有接受 const 流的 operator>> 版本。
【解决方案2】:

使用非常量引用:

void foo(std::istream& in) {
  std::string tmp;
  while(in >> tmp) {
     std::cout << tmp;
  }
}

【讨论】:

    【解决方案3】:

    运算符>>修改流,所以不要通过const,只是一个引用。

    【讨论】:

    • 谢谢!令人惊讶的是,从流中读取应该会修改它,但可能是位置指针通过读取而前进。
    • 这不足为奇。现在从流中读取会改变您稍后将从同一流中读取的内容。这是一个可观察到的外部效果,因此应该考虑修改对象,而不管位置指针的内部实现细节如何。
    猜你喜欢
    • 2011-09-13
    • 2017-05-31
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2010-12-21
    • 2014-01-05
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多