From fc86917da1a175c04e9bd2e5f0bedb0a48a81c26 Mon Sep 17 00:00:00 2001 From: Willem Jan Palenstijn Date: Thu, 17 Dec 2015 14:37:41 +0100 Subject: Replace boost::lexical_cast by stringstreams This is to avoid the dependence of lexical_cast on the current locale. The stringstreams used for the new string parsing/output functions are explicitly imbued with the C/classic locale. --- src/Utilities.cpp | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) (limited to 'src/Utilities.cpp') diff --git a/src/Utilities.cpp b/src/Utilities.cpp index cb54e93..4b80503 100644 --- a/src/Utilities.cpp +++ b/src/Utilities.cpp @@ -28,4 +28,99 @@ $Id$ #include "astra/Utilities.h" +#include +#include +#include +#include +#include +#include + +namespace astra { + +namespace StringUtil { + +int stringToInt(const std::string& s) +{ + double i; + std::istringstream iss(s); + iss.imbue(std::locale::classic()); + iss >> i; + if (iss.fail() || !iss.eof()) + throw bad_cast(); + return i; + +} + +float stringToFloat(const std::string& s) +{ + return (float)stringToDouble(s); +} + +double stringToDouble(const std::string& s) +{ + double f; + std::istringstream iss(s); + iss.imbue(std::locale::classic()); + iss >> f; + if (iss.fail() || !iss.eof()) + throw bad_cast(); + return f; +} + +template<> float stringTo(const std::string& s) { return stringToFloat(s); } +template<> double stringTo(const std::string& s) { return stringToDouble(s); } + +std::vector stringToFloatVector(const std::string &s) +{ + return stringToVector(s); +} + +std::vector stringToDoubleVector(const std::string &s) +{ + return stringToVector(s); +} + +template +std::vector stringToVector(const std::string& s) +{ + // split + std::vector items; + boost::split(items, s, boost::is_any_of(",;")); + + // init list + std::vector out; + out.resize(items.size()); + + // loop elements + for (unsigned int i = 0; i < items.size(); i++) { + out[i] = stringTo(items[i]); + } + return out; +} + + +std::string floatToString(float f) +{ + std::ostringstream s; + s.imbue(std::locale::classic()); + s << std::setprecision(9) << f; + return s.str(); +} + +std::string doubleToString(double f) +{ + std::ostringstream s; + s.imbue(std::locale::classic()); + s << std::setprecision(17) << f; + return s.str(); +} + + +template<> std::string toString(float f) { return floatToString(f); } +template<> std::string toString(double f) { return doubleToString(f); } + + +} + +} -- cgit v1.2.3