简体   繁体   中英

std::cin.readsome always reading 0 bytes

I did a simple test with C++ code and using the helper tool pv (pipe viewer). The code is:

#include <iostream>
#include <array>

int main() {
    std::array<char,4096> buffer;
    while( true ) {
        std::cin.readsome(buffer.data(),4096);
    }
}

I execute with:

pv /dev/urandom | ./a.out

Through pv , I notice that readsome never reads anything. What am I missing?

Please see cppreference , especially under "Notes".

The behavior of this function is highly implementation-specific. For example, when used with std::ifstream , some library implementations fill the underlying filebuf with data as soon as the file is opened (and readsome() on such implementations reads data, potentially, but not necessarily, the entire file), while other implementations only read from file when an actual input operation is requested (and readsome() issued after file opening never extracts any characters). Likewise, a call to std::cin.readsome() may return all pending unprocessed console input, or may always return zero and extract no characters.

However, if I try this with:

std::cin >> buffer.data();

Then I can extract the console input. In order to get the behavior you are seeking, I would use std::istream::get() , and check the eof and fail bits in your while loop.

readsome() terminates when its buffer is exhausted, in order to avoid delays. If you don't already have data waiting for the call by the time you execute it, it won't read anything. It won't wait for you.

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