From 261ba26d27c3a64a627b6f407e057da0d17b621c Mon Sep 17 00:00:00 2001 From: Mathias Gumz Date: Thu, 1 Oct 2009 21:16:46 +0200 Subject: another little helper for FbTk::StringUtil: extractNumber() --- src/FbTk/StringUtil.cc | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/FbTk/StringUtil.hh | 8 ++++++++ src/Layer.hh | 2 +- 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/FbTk/StringUtil.cc b/src/FbTk/StringUtil.cc index a0e402d..639041b 100644 --- a/src/FbTk/StringUtil.cc +++ b/src/FbTk/StringUtil.cc @@ -48,6 +48,11 @@ #include #endif +#ifdef HAVE_CERRNO + #include +#else + #include +#endif #include #include @@ -56,10 +61,51 @@ using std::string; using std::transform; +namespace { + +int extractLongNumber(const char* in, long long int& out) { + + errno = 0; + + int ret = 0; + char* end = 0; + long long int result = strtoll(in, &end, 0); + + if (errno == 0 && end != in) { + out = result; + ret = 1; + } + + return ret; +} + +template +int extractNumber(const std::string& in, T& out) { + + long long int result = 0; + + if (::extractLongNumber(in.c_str(), result) && out >= 0) { + out = static_cast(result); + return 1; + } + + return 0; +} + +} + + namespace FbTk { namespace StringUtil { +int extractNumber(const std::string& in, int& out) { + return ::extractNumber(in, out); +} + +int extractNumber(const std::string& in, unsigned int& out) { + return ::extractNumber(in, out); +} std::string number2String(int num) { char s[128]; diff --git a/src/FbTk/StringUtil.hh b/src/FbTk/StringUtil.hh index 6493f74..7bc8f80 100644 --- a/src/FbTk/StringUtil.hh +++ b/src/FbTk/StringUtil.hh @@ -30,6 +30,14 @@ namespace FbTk { namespace StringUtil { +/// \@{ +/// @param in - input string, might be 0xab or 0123 +/// @param out - result if extraction was ok +/// @return 1 - ok, result stored in 'out' +int extractNumber(const std::string& in, unsigned int& out); +int extractNumber(const std::string& in, int& out); +/// \@} + /// creates a number to a string std::string number2String(int num); diff --git a/src/Layer.hh b/src/Layer.hh index 14054b0..9aaca0a 100644 --- a/src/Layer.hh +++ b/src/Layer.hh @@ -48,7 +48,7 @@ public: static int getNumFromString(const std::string &str) { int tempnum = 0; std::string v = FbTk::StringUtil::toLower(str); - if (sscanf(str.c_str(), "%d", &tempnum) == 1) + if (FbTk::StringUtil::extractNumber(str, tempnum)) return tempnum; if (v == "menu") return ::Layer::MENU; -- cgit v0.11.2