I get an object ( msg.data
) that is either a number or a string. If it is a string I don't want to use it, if it is a number I want to. I currently solved this problem with an ostringstream
, though I think there are way better solutions:
void scan_cb(const sensor_msgs::LaserScan::ConstPtr& scan)
{
float dist = 0.0f;
std::ostringstream s;
s << scan->ranges[0]; // can be string (always "inf") or a float
if(s.str() != "inf"){
dist += scan->ranges[0];
}
...
I care about efficiency, because this is part of a for loop running many times each second.
The basic structure is a ROS message, coming from a certain topic, and can have basically any data type. In this case I use a LaserScan message , the documentation does not mention that range[x]
can return "inf" .
According to ROS documentation, scan->ranges
is an array of float. That makes sense, because you add it to a float ( dist
) when the string representation of ranges[0]
is not inf
.
That means that (as MSalters guessed in its comment), you have a true float value, and you just want to make sure it is a real number and neither an infinite value nor a NaN (Not a Number) value.
So provided you include cmath
(or math.h
) you can use the C classifications macros to determine whether the number is finite (but subnormal values are allowed) or normal (even subnormal values are rejected):
void scan_cb(const sensor_msgs::LaserScan::ConstPtr& scan)
{
float dist = 0.0f;
if(isfinite(scan->ranges[0])){
dist += scan->ranges[0];
}
...
(more references on IEEE-754 representation of floating point numbers on wikipedia )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.