Extracting integers from strings without sstream C ++

What is the easiest way to extract the following integers from a string, for example: "54 232 65 12".

And what if the last number is a long long int. Is it possible to do this without sstream

+4
source share
1 answer

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 .)

+5
source

Source: https://habr.com/ru/post/1485117/


All Articles