使用operator >>两次后为什么std :: getline失败?(why does std::getline fails after using operator>>

编程入门 行业动态 更新时间:2024-10-28 18:25:57
使用operator >>两次后为什么std :: getline失败?(why does std::getline fails after using operator>> twice?)

我有给定的输入:

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 >> ip >> domain; )时会出现此问题。 如果我有cin >> ip ,代码就像我期望的那样工作。 当我使用std::getline双提取( operator>> )时,为什么会看到这个奇怪的结果?

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. The code works as I would expect if I had cin >> ip. Why am I seeing this weird result when I use double extraction(operator>>) with std::getline?

最满意答案

流operator>>提取它提取的数据之前的空白,而不是之后。 这意味着它将“localhost”提取到domain ,但在流中留下新行。 getline()然后只读取这个换行符。

Stream operator>> extracts whitespace which is before the data it extracts, not after. This means it extracts "localhost" into domain, but leaves following the newline in the stream. getline() then reads just this newline.

更多推荐

本文发布于:2023-08-02 03:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1369404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   后为   operator   fails   getline

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!