another little helper for FbTk::StringUtil: extractNumber()
Mathias Gumz akira at fluxbox dot org
3 files changed,
55 insertions(+),
1 deletions(-)
M
src/FbTk/StringUtil.cc
→
src/FbTk/StringUtil.cc
@@ -48,6 +48,11 @@ #else
#include <string.h> #endif +#ifdef HAVE_CERRNO + #include <cerrno> +#else + #include <errno.h> +#endif #include <memory> #include <algorithm>@@ -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<typename T> +int extractNumber(const std::string& in, T& out) { + + long long int result = 0; + + if (::extractLongNumber(in.c_str(), result) && out >= 0) { + out = static_cast<T>(result); + return 1; + } + + return 0; +} + +} + + namespace FbTk { namespace StringUtil { +int extractNumber(const std::string& in, int& out) { + return ::extractNumber<int>(in, out); +} + +int extractNumber(const std::string& in, unsigned int& out) { + return ::extractNumber<unsigned int>(in, out); +} std::string number2String(int num) { char s[128];
M
src/FbTk/StringUtil.hh
→
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);
M
src/Layer.hh
→
src/Layer.hh
@@ -48,7 +48,7 @@
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;