another little helper for FbTk::StringUtil: extractNumber()

This commit is contained in:
Mathias Gumz 2009-10-01 21:16:46 +02:00
parent 57b6e5a778
commit 261ba26d27
3 changed files with 55 additions and 1 deletions

View file

@ -48,6 +48,11 @@
#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];

View file

@ -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);

View file

@ -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;