Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::istream_iterator ignores newline characters?

Tags:

c++

I have the following code:

#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
    std::stringstream str; str << "abc\ndef";

    std::cout << "[" << str.str() << "]" << std::endl;

    std::istream_iterator<char> it(str), end;

    for (; it != end; ++it)
    {
        std::cout << "[" << unsigned(*it) << "]";
    }

    std::cout << std::endl;

    return 0;
}

And the output is:

[abc
def]
[97][98][99][100][101][102]

Why std::istream_iterator ignored the new-line character?

like image 413
chila Avatar asked Jan 21 '14 20:01

chila


1 Answers

Because istream_iterator uses operator>>. And istream::operator>>(char) skips whitespace, unless you unset the skipws flag of the stream. (e.g. using noskipws)

It's the same output you would get if you did this:

char c;
while (str >> c)
    std::cout << "[" << unsigned(c) << "]";
like image 114
Benjamin Lindley Avatar answered Oct 17 '22 16:10

Benjamin Lindley