I would probably use a locale that treats everything except numbers as white space, and read numbers from a string stream saturated with this locale, and check if they are in the range:
#include <iostream> #include <algorithm> #include <locale> #include <vector> #include <sstream> struct digits_only: std::ctype<char> { digits_only(): std::ctype<char>(get_table()) {} static std::ctype_base::mask const* get_table() { static std::vector<std::ctype_base::mask> rc(std::ctype<char>::table_size,std::ctype_base::space); std::fill(&rc['0'], &rc['9'], std::ctype_base::digit); return &rc[0]; } }; bool in_range(int lower, int upper, std::string const &input) { std::istringstream buffer(input); buffer.imbue(std::locale(std::locale(), new digits_only())); int n; while (buffer>>n) if (n < lower || upper < n) return false; return true; } int main() { std::cout << std::boolalpha << in_range(5, 35, "XDGHYH20YFYFFY"); return 0; }
source share