std::cin.readsome always reading 0 bytes

跟風遠走 提交于 2019-12-07 15:29:37

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24700586/stdcin-readsome-always-reading-0-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!