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

ROS_INFO a String

asked 2022-07-19 04:07:42 -0500

sajid1122 gravatar image

updated 2022-07-19 21:03:11 -0500

hi there, this is a question with regards to the "Writing publisher subscriber" tutorial with c++. I've realized that for strings we have to add in .c_str()

What is this .c_str() thing? We add it in when


why cant we just.


And i've also realized this is specific only for strings. Thanks in advanced to whoever helped me out :)

edit: I did my own personal reading and found a few resources pretty helpful in understanding this. check out

Enjoy :)

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-07-19 04:41:02 -0500

ljaniec gravatar image

updated 2022-07-19 04:42:40 -0500

By the C++ documentation:

const char* c_str() const noexcept;

Get C string equivalent

Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

Return Value

A pointer to the c-string representation of the string object's value.

c_str returns a const char* that points to a null-terminated string (i.e. a C-style string).

It is useful when you want to pass the "contents" of a std::string to a function that expects to work with a C-style string.

edit flag offensive delete link more


Hi, thanks for your. Answer, very helpful. But i have a followup question.

Why do we have to pass the string pointer and not the string as a whole. coz like you mentioned, the return value is a pointer to the c-string. Why do we need to return a pointer? why cant we just return the actual string itself.

Anyways, your answer was very helpful. Do answer my follow-up question when you get the chance if not its alright too :)

sajid1122 gravatar image sajid1122  ( 2022-07-19 07:01:31 -0500 )edit

I based my answer on similar questions in the past, e.g.

A string type in a ROS message/service maps to a std::string in C++ (see the msg package for more details). std::string's are not printable with something like printf, unless you get access to the underlying const char* data which is what printf's "%s" format string is expecting. You can get access to the C-string via the c_str() member on std::string.

ljaniec gravatar image ljaniec  ( 2022-07-19 07:16:15 -0500 )edit

Yup, thanks for sharing that link. I think that answers my question. Thanks a lot mate.

sajid1122 gravatar image sajid1122  ( 2022-07-19 07:18:33 -0500 )edit

Question Tools

1 follower


Asked: 2022-07-19 04:07:42 -0500

Seen: 177 times

Last updated: Jul 19 '22