Reputation: 8915
What does 20
inside message()
mean vs the 20
after message.data(),
in the below code?
zmq::message_t message(20);
snprintf ((char *) message.data(), 20 ,"%05d %d %d", zipcode, temperature, relhumidity);
publisher.send(message);
From reading the documentation, message(20)
initialises the message to be 20 bytes long. What does the 20
after message.data(),
do?
How to change the size of the message to send the message without trailing bytes \x00
? Can "%05d %d %d", zipcode, temperature, relhumidity
be declared outside and the length of that variable be used to initiate the message and send it?
Upvotes: 0
Views: 324
Reputation: 168988
You can use snprintf()
with a limit of zero to measure how large the data will be before allocating the space for it:
auto length = std::snprintf(nullptr, 0, "%05d %d %d", zipcode, temperature, relhumidity) + 1;
// +1 to account for null terminating character.
zmq::message_t message(length);
std::snprintf(
static_cast<char *>(message.data()), length,
"%05d %d %d", zipcode, temperature, relhumidity
);
publisher.send(message);
You could also format into a local buffer that you know is large enough, measure the string's length, then copy it:
char buffer[64];
auto length = std::snprintf(buffer, 64, "%05d %d %d", zipcode, temperature, relhumidity) + 1;
zmq::message_t message(length);
std::copy(buffer, buffer + length, static_cast<char *>(message.data());
publisher.send(message);
Upvotes: 1