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
?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.