Skip to content

Commit

Permalink
adding invalid_argument check.
Browse files Browse the repository at this point in the history
  • Loading branch information
bailaC committed Jan 11, 2024
1 parent 65d4fd1 commit 983dc47
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#define HARDWARE_INTERFACE__LEXICAL_CASTS_HPP_

#include <locale>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
Expand Down
18 changes: 16 additions & 2 deletions hardware_interface/src/lexical_casts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@

namespace hardware_interface
{
double stod(const std::string & s)
namespace impl
{
std::optional<double> stod(const std::string & s)
{
#if __cplusplus < 202002L
// convert from string using no locale
// Impl with std::istringstream
std::istringstream stream(s);
stream.imbue(std::locale::classic());
double result;
Expand All @@ -30,16 +33,27 @@ double stod(const std::string & s)
}
return result;
#else
// Impl with std::from_chars
double result_value;
const auto parse_result = std::from_chars(s.data(), s.data() + s.size(), result_value);
if (parse_result.ec == std::errc())
{
return result_value;
}

return 0.0;
return std::nullopt;
;
#endif
}
} // namespace impl
double stod(const std::string & s)
{
if (const auto result = impl::stod(s))
{
return *result;
}
throw std::invalid_argument("Failed converting string to real number");
}
bool parse_bool(const std::string & bool_string)
{
return bool_string == "true" || bool_string == "True";
Expand Down

0 comments on commit 983dc47

Please sign in to comment.