You can do it quite simply by using a function to location the first occurrence of a digit in your string. Including <cstring>
makes strspn()
available and makes the process trivial.
For example to find the first digit character in "a15a"
you can simply make the call:
int a;
size_t off, pos;
std::string x = "a15a";
off = strcspn (x.c_str(), "0123456789"); /* get no. chars to 1st digit */
off
now holds the offset to the first digit in x
. The conversion at that point is simple, but to validate the conversion you must use the try {...} catch (exception) {...}
format or you will not know whether the value a
after the attempted conversion is valid or not, e.g.
try { /* validate using try {..} catch (exception) {..} */
a = std::stoi(x.c_str() + off, &pos); /* good conversions, store a */
std::cout << a << '\n'; /* output number in "a15a" */
}
catch (const std::exception & e) {
std::cerr << e.what() << '\n';
return 1;
}
That's all that is required to locate the start of the digits in x
and then to validate the conversion at x + off
to arrive at the desired integer value.
Putting it altogether, you would have:
#include <iostream>
#include <string>
#include <cstring>
int main() {
int a;
size_t off, pos;
std::string x = "a15a";
off = strcspn (x.c_str(), "0123456789"); /* get no. chars to 1st digit */
try { /* validate using try {..} catch (exception) {..} */
a = std::stoi(x.c_str() + off, &pos); /* good conversions, store a */
std::cout << a << '\n'; /* output number in "a15a" */
}
catch (const std::exception & e) {
std::cerr << e.what() << '\n';
return 1;
}
}
Example Use/Output
$ /bin/stoi_int
15