I know this is a repeated question, and I a have looked at a lot of answers for it but none have really been able to help me so far.
I need to be able to pass various strings into two methods one returns a double and the other a int. The main problem is that I need strict error checking on both methods so that if I pass a string that dose not contain a number and only a number the method does not make a conversion. As I said I've seen a few solutions but the only good one I've seen (that was able to follow) was using Boost which I do not want to use. As for the answer I was not able to follow here is a part of it copied from
How to parse a string to an int in C++?
The best solution
Fortunately, somebody has already solved all of the above problems. The C standard library contains strtol
and family which have none of these problems.
enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
STR2INT_ERROR str2int (int &i, char const *s, int base = 0)
{
char *end;
long l;
errno = 0;
l = strtol(s, &end, base);
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {
return OVERFLOW;
}
if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {
return UNDERFLOW;
}
if (*s == '\0' || *end != '\0') {
return INCONVERTIBLE;
}
i = l;
return SUCCESS;
}
If anyone can explain it a little more I think it is the answer Im looking for I just cant get enough of a grasp of what its doing so that i can apply the idea to my code.