chila
chila

Reputation: 2442

Why std::istream_iterator ignores newline characters?

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?

Upvotes: 6

Views: 2412

Answers (3)

Jay Yang
Jay Yang

Reputation: 413

Use std::istreambuf_iterator<char> instead, it won't loss spaces and newlines.

Upvotes: 5

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

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) << "]";

Upvotes: 10

smac89
smac89

Reputation: 43128

You can disable skipping any whitespace in the input by changing a little bit of your code:

std::stringstream str; str << std::noskipws << "abc\ndef";

New output:

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

Upvotes: 5

Related Questions