gpt4 book ai didi

c++ - 如何修复 ZeroMQ 发布者 C++ 中的运行时错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:17 27 4
gpt4 key购买 nike

我尝试使用 C++ 在 ZeroMQ 中开发发布者订阅者模型,我从 JSON 文件中提取对象值并将其发送到另一端。

我的订户部分运行良好,但出现任何错误。但是我在发布者部分面临以下错误:(在 if 语句中)

    src/lib_json/json_value.cpp:1136: Json::Value& 
Json::Value::resolveReference(const char*, bool): Assertion `type_ ==
nullValue || type_ == objectValue' failed.
Aborted (core dumped)

这是我的发布者代码:

    #include "jsoncpp/include/json/value.h"
#include "jsoncpp/include/json/reader.h"
#include <fstream>
#include "cppzmq/zmq.hpp"
#include <string>
#include <iostream>
#include <unistd.h>

using namespace std;

int main () {
zmq::context_t context(1);
zmq::socket_t publisher (context, ZMQ_PUB);
int sndhwm = 0;
publisher.setsockopt (ZMQ_SNDHWM, &sndhwm, sizeof (sndhwm));
publisher.bind("tcp://*:5561");
const Json::Value p;
ifstream pub_file("counter.json");
Json::Reader reader;
Json::Value root;

if(pub_file != NULL && reader.parse(pub_file, root)) {
const Json::Value p = root ["body"]["device_data"]["device_status"];
}

string text = p.asString();
zmq::message_t message(text.size());
memcpy(message.data() , text.c_str() , text.size());
zmq_sleep (1);
publisher.send(message);
return 0;
}

最佳答案

const Json::Value p;
...
if(pub_file != NULL && reader.parse(pub_file, root)) {
const Json::Value p = root ["body"]["device_data"]["device_status"];
}

string text = p.asString();

当您在 if 语句中创建 another p 时,这个新声明的变量仅对条件 {} 代码块的范围。将其更改为对已声明变量 p 的干净赋值:

p = root ["body"]["device_data"]["device_status"];

这会更改外部范围内的变量,而不是在内部范围内声明一个新变量。此外,您应该将变量 const Json::Value p 标记为 not const,以便您可以在条件语句中修改它。

关于c++ - 如何修复 ZeroMQ 发布者 C++ 中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155948/

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