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

Revision history [back]

click to hide/show revision 1
initial version

I think the main problem is that printf's %s formatter expects a C-style string, not a C++ string. All you'd have to do to fix this is:

printf ( "Topic %d is: %s.\n", i, static_cast<std::string>(my_list[i]).c_str() );

Note the addition of the .c_str() function call.

Also, you might want to change printf to ROS_INFO. All of the formatting is the same, but it has cool ROS functionality.

I think the main problem is that printf's %s formatter expects a C-style string, not a C++ string. All you'd have to do to fix this is:

printf ( "Topic %d is: %s.\n", i, static_cast<std::string>(my_list[i]).c_str() );

Note the addition of the .c_str() function call.

Also, you might want to change printf to ROS_INFO. All of the formatting is the same, but it has cool ROS functionality.

EDIT: Here's a quick explanation. Since printf is the output format used in C, not in C++, it expects that you'd be using C-style data structures. The %s formatter in C expects that you will pass in a const char*, which is C's representation of a string - an array of characters. In C++, however, the std::string data structure is more complex than a const char* and is its own type entirely. It's essentially the same as trying to use a double with %s. It's the wrong datatype, and therefore will not work. The .c_str() method of a C++ std::string returns a const char* of the string so that you can use it with C functions.

I think the main problem is that printf's %s formatter expects a C-style string, not a C++ string. All you'd have to do to fix this is:

printf ( "Topic %d is: %s.\n", i, static_cast<std::string>(my_list[i]).c_str() );

Note the addition of the .c_str() function call.

Also, you might want to change printf to ROS_INFO. All of the formatting is the same, but it has cool ROS functionality.

EDIT: Here's a quick explanation. Since printf is the output format used in C, not in C++, it expects that you'd be using C-style data structures. The %s formatter in C expects that you will pass in a const char*, which is C's representation of a string - an array of characters. In C++, however, the std::string data structure is more complex than a const char* and is its own type entirely. It's essentially the same as trying to use a double with %s. It's the wrong datatype, and therefore will not work. The .c_str() method of a C++ std::string returns a const char* of the string so that you can use it with C functions.

The block of code static_cast<std::string>(my_list[i]) returns a std::string, and thus you cannot use it with %s. static_cast<std::string>(my_list[i]) is one of C++'s forms of casting my_list[i] to an std::string. static_cast<double>(my_list[i]) would cast it to a double.