gpt4 book ai didi

c++ - std::cin.readsome 始终读取 0 字节

转载 作者:太空狗 更新时间:2023-10-29 21:20:22 25 4
gpt4 key购买 nike

我用 C++ 代码和辅助工具 pv(管道查看器)做了一个简单的测试。代码是:

#include <iostream>
#include <array>

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

我执行:

pv /dev/urandom | ./a.out

通过 pv,我注意到 readsome 从不读取任何内容。我错过了什么?

最佳答案

请参阅cppreference ,尤其是在“注释”下。

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.

但是,如果我尝试这样做:

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

然后我可以提取控制台输入。为了获得您正在寻找的行为,我会使用 std::istream::get(),并检查 eoffail while 循环中的位。

关于c++ - std::cin.readsome 始终读取 0 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24700586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com