c++ - std::getline skipping input from std::cin after last occurrence of delimiter, but not with input from std::istringstream -
i need read input delimited whitespace, main construction used is:
while(std::getline(std::cin, s, ' ')){ std::cout << s << std::endl; }
for input: "this text"
output s be: "this", "is", "some", skipping last piece of input after last whitespace.
want include last piece of input in program well, went looking solution , found following:
while (std::getline(std::cin, line)) { std::istringstream iss(line); while (std::getline(iss, s, ' ')) { std::cout << s << std::endl; } }
for input: "this text"
the output s be: "this", "is", "some", "text", want.
my question is: why reading std::cin delimiter skip input after last occurrence of delimiter, reading std::istringstream not?
my question is: why reading
std::cin
delimiter skip input after last occurrence of delimiter, readingstd::istringstream
not?
it doesn't.
in first example:
while(std::getline(std::cin, s, ' ')){ std::cout << s << std::endl; }
you reading items newline literally delimited single space. because line (ostensibly) ended newline, never finish extracting input string expecting either ' '
or eof.
in second example:
while (std::getline(std::cin, line)) { std::istringstream iss(line); while (std::getline(iss, s, ' ')) { std::cout << s << std::endl; } }
the std::getline
in first while strip newline example sentence. items extracted according basic rules.
here rules (from cppreference):
extracts characters input , appends them str until 1 of following occurs (checked in order listed) a) end-of-file condition on input, in case, getline sets eofbit. b) next available input character delim, tested traits::eq(c, delim), in case delimiter character extracted input, not appended str. c) str.max_size() characters have been stored, in case getline sets failbit , returns.
Comments
Post a Comment