简体   繁体   中英

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?

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

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

char c;
while (str >> c)
    std::cout << "[" << unsigned(c) << "]";

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]

改用std::istreambuf_iterator<char> ,它不会丢失空格和换行符。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM