I am writing a program wherein I need to turn a character array into an integer. However, instead of just using the positive integers, I need to utilize the full potential of all the integers (in the range of capability of the type int
of course) (i.e: positive, negative, and 0). But I need access to some sentinel value, very much so preferably within the type int
. I don't want to have to make everything float
just so I can use one noninteger sentinel, if I can avoid it.
To solve this problem temporarily, I've just been using the following "trick": (where token
is the array)
int TokenToInt(char token[])
{
int current=0, value=0;
char isNeg = 'F';
if (token[current] == '-') {
isNeg = 'T';
current++;
}
while (1) {
if (isdigit(token[current]) == 0)
return -1;
else {
value *= 10;
value += token[current]-'0';
}
current++;
}
if (isNeg == 'F') return value;
if (isNeg == 'T') return -1 * (value + 1);
}
So in the rest of the program, you use -1
for error checking, and once you're done with that, increment the returned value if it's negative. Which works, except possibly if the user inputs -2^15
, but better not be able to input that than -1
, right?
But it's also cumbersome, and kind of confusing to just randomly increment the value out of the blue. So should I stick with this ^ method or is there an alternative that accomplishes the same task? If there is an alternative, what is this alternative?