First time here? Check out the FAQ!


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

Using if statements with std_msgs::String::ConstPtr

asked Oct 12 '13

Alkaros gravatar image

updated Apr 20 '14

ngrennan gravatar image

I have a node that is getting action calls from another node. Once it gets the action, I want to call a specific function but the if statement doesn't ever return true.

How can I get an if statement to work with a std_msgs string?

void chattersCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: %s", msg->data.c_str());
  if ((msg->data.c_str()) == "Listen") {sendStopAction();}
}

The terminal shows

[ INFO] [1381550860.740367371]: I heard: Listen

But the If statement does not return true. There is another print statement in the sendStopAction() function

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered Oct 12 '13

Dirk Thomas gravatar image

I guess your code example should be:

if (msg->data.c_str() == "Listen") ...

In C++ you can not just compare two char*. You neither have to use strcmp() or use the comparison operator of std::string:

if (msg->data == "Listen") ...
Preview: (hide)

Comments

Thank you. Yes, my code was msg->data.c_str(). I got confused and tried dropping the c_ just to see if it magically changed anything. Thanks again :)

Alkaros gravatar image Alkaros  ( Oct 12 '13 )edit

Question Tools

1 follower

Stats

Asked: Oct 12 '13

Seen: 4,821 times

Last updated: Oct 11 '13