【问题标题】:why does std::getline fails after using operator>> twice?为什么 std::getline 在使用 operator>> 两次后会失败?
【发布时间】:2013-03-17 18:14:10
【问题描述】:

我有给定的输入:

 local
 127.0.0.1 localhost
 other
 next

使用下面的代码,输出是我期望其他的空白。输出为“输出:”

#include <iostream>
using namespace std;

int main() {
    std::string ip, domain, header;
    std::getline(cin, header);
    cin >> ip >> domain;
    std::getline(cin, header);
    std::cout << "output: " << header;
}

但是,我注意到在调用 std::getline 之前提取两次 (cin &gt;&gt; ip &gt;&gt; domain;) 时会出现此问题。如果我有cin &gt;&gt; ip,代码会像我预期的那样工作。为什么我在使用双重提取(operator&gt;&gt;)和std::getline 时会看到这个奇怪的结果?

【问题讨论】:

  • 您的输入中有空行吗?请使用代码格式格式化帖子以使其明确。

标签: c++ operators getline extraction


【解决方案1】:

Stream operator&gt;&gt; 提取空格,它是之前它提取的数据,而不是之后。这意味着它将“localhost”提取到domain,但在流中跟随换行符。 getline() 然后只读取这个换行符。

【讨论】:

  • 这是正确的。当我使用std::getline(cin, header); 两次时,我得到了正确的结果。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多