C: signed integer sentinel value? -
i writing program wherein need turn character array integer. however, instead of using positive integers, need utilize full potential of integers (in range of capability of type int of course) (i.e: positive, negative, , 0). need access sentinel value, very so preferably within type int. don't want have make float can use 1 noninteger sentinel, if can avoid it.
to solve problem temporarily, i've been using following "trick": (where token 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 rest of program, use -1 error checking, , once you're done that, increment returned value if it's negative. works, except possibly if user inputs -2^15, better not able input -1, right?
but it's cumbersome, , kind of confusing randomly increment value out of blue. should stick ^ method or there alternative accomplishes same task? if there alternative, alternative?
if red correctly, you're saying need return int, need able detect error. there 2 common ways of doing this: putting return value in argument passed reference, or adding method set/get errors.
for first, like
int myfcn(int* result, char[] input) { // stuff ... if( success ) { *result = ...; return error_success; } else { return error; } } the second like...
void caller() { int value = tokentoint(...); if( getlasterror() != error_success ) { // handle error } } int tokentoint(...) { // stuff if( error ) { setlasterror(error_whatever); return result } return result; } you can getlasterror function additional details.
Comments
Post a Comment