ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How do I get the length of a String in C++?

asked 2018-02-08 19:05:43 -0500

kylerlaird gravatar image

I'm sending binary data as a String. It's easy to publish it and read it in Python, but I'm trying to extend a driver that's written in C++ (and I have very little C++ experience). I made it work by using this ugly kludge in the topic subscriber.

uint32_t string_length = ros::serialization::serializationLength(*msg) - 4;

I was hoping that there would be a length value in the message but according to http://wiki.ros.org/ROS/Tutorials/Wri... String only has one member, "data". Is there a clean way to get the length of the data?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2018-02-08 22:45:54 -0500

ahendrix gravatar image

Similar to python's len() method for determining the length of a string, the std::string object in C++ has a length() member function that returns the length of the string. (See: http://www.cplusplus.com/reference/st... for more complete documentation of std::string)

Since the string in a std_msgs/String message is represented with a std::string in C++, if you have a pointer to a std_msgs::String (the C++ type for std_msgs/String) you can get the string's length with msg->data.length().

edit flag offensive delete link more

Comments

Perfect. That is exactly the answer I needed and the reference will help me with other work. I updated the code and it works as expected. Thank you!

kylerlaird gravatar image kylerlaird  ( 2018-02-09 08:04:10 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2018-02-08 19:05:43 -0500

Seen: 1,142 times

Last updated: Feb 08 '18