gpt4 book ai didi

c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题

转载 作者:行者123 更新时间:2023-11-30 04:32:47 31 4
gpt4 key购买 nike

我在读取通过 asyc_read() 填充的 streambuf 时遇到了一些问题。在 VS 中单步执行我的代码时,我可以看到缓冲区中有正确的数据,但是当我去读取它时:

std::istream is = std::istream(&buffer_);

unsigned short type;
unsigned short size;

is >> type;
is >> size;

type 和 size 变量保持在它们的初始值。没有错误或任何东西被抛出。我真的很困惑为什么会这样我已经看到类似的代码以完全相同的方式将数据读入变量

编辑:所以这是我的 async_read 代码,然后调用上面的代码:

boost::asio::async_read(socket_,
buffer_,
boost::asio::transfer_at_least(4),
boost::bind(&Session::handleReadBody, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));

最佳答案

如果 type 保持其初始值,则很明显 是 >> 类型; 失败:检查流的状态 (if(is) { ...) 可以肯定。

并且,鉴于您有一个 transfer_at_least(4),我怀疑您正在传输二进制数据,而不是以空格分隔的 ASCII 字符串。如果是这种情况,请使用 read():

int16_t type, size;
data.read(reinterpret_cast<char*>(&type), sizeof type);
data.read(reinterpret_cast<char*>(&size), sizeof size);

但要注意字节顺序。

关于c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397019/

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