我有给定的输入:
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 nextUsing 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.
更多推荐
发布评论