简体   繁体   中英

Why does std::operator>>(istream&, char&) extract whitespace?

I was compiling the following program and I learned that the extractor for a char& proceeds to extract a character even if it is a whitespace character. I disabled the skipping of leading whitespace characters expecting the proceeding read attempts to fail (because formatted extraction stops at whitespace), but was surprised when it succeeded.

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("a b c");
    char a, b, c;

    iss >> std::noskipws;

    if (iss >> a >> b >> c)
    { 
        std::cout <<     "a = \"" << a
                  << "\"\nb = \"" << b
                  << "\"\nc = \"" << c << '\n';
    }
}

Output:

 a = "a" b = " " c = "b" 

As you can see from the output, b was given the value of the space between "a" and "b" ; and c was given the following character "b" . I was expecting both b and c to not have a value at all since the extraction should fail because of the leading whitespace. What is the reason for this behavior?

In IOStreams, characters have virtually no formatting requirements. Any and all characters in the character sequence are valid candidates for an extraction. For the extractors that use the numeric facets, extraction is defined to stop at whitespace. However, the extractor for charT& works directly on the buffer, indiscriminately returning the next available character presumably by a call to rdbuf()->sbumpc() .

Do not assume that this behavior extends to the extractor for pointers to characters as for them extraction is explicitly defined to stop at whitespace.

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