简体   繁体   English

使用operator >>两次后为什么std :: getline失败?

[英]why does std::getline fails after using operator>> twice?

I have the given input: 我有给定的输入:

 local
 127.0.0.1 localhost
 other
 next

Using the following code the output is a blank where I expected other . 使用以下代码,输出是一个空白,我期望其他 The output is "output: " 输出是“输出:”

#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;
}

However, I notice this problem occurs when extracting twice ( cin >> ip >> domain; ) before calling std::getline . 但是,我注意到在调用std::getline之前提取两次( cin >> ip >> domain; )时会出现此问题。 The code works as I would expect if I had cin >> ip . 如果我有cin >> ip ,代码就像我期望的那样工作。 Why am I seeing this weird result when I use double extraction( operator>> ) with std::getline ? 当我使用std::getline双提取( operator>> )时,为什么会看到这个奇怪的结果?

Stream operator>> extracts whitespace which is before the data it extracts, not after. operator>>提取它提取的数据之前的空白,而不是之后。 This means it extracts "localhost" into domain , but leaves following the newline in the stream. 这意味着它将“localhost”提取到domain ,但在流中跟随换行符。 getline() then reads just this newline. getline()然后只读取这个换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM