简体   繁体   English

为什么 std::istream_iterator 忽略换行符?

[英]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?为什么 std::istream_iterator 忽略了换行符?

Because istream_iterator uses operator>> .因为istream_iterator使用operator>> And istream::operator>>(char) skips whitespace, unless you unset the skipws flag of the stream.并且istream::operator>>(char)跳过空格,除非您取消设置流的skipws标志。 (eg using noskipws ) (例如使用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> ,它不会丢失空格和换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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