Try the following:
#include <cstdlib> #include <cstdio> #include <cerrno> #include <cstring> int main() { char str[] = " 2 365 2344 1234444444444444444444567 43"; for (char * e = str; *e != '\0'; ) { errno = 0; char const * s = e; unsigned long int n = strtoul(s, &e, 0); if (errno) // conversion error (eg overflow) { std::printf("Error (%s) encountered converting:%.*s.\n", std::strerror(errno), e - s, s); continue; } if (e == s) { ++e; continue; } // skip inconvertible chars s = e; printf("We read: %lu\n", n); } }
In C ++ 11, you can also use std::strtoull , which returns an unsigned long long int .
( Live example .)
source share