Question

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?

Was it helpful?

Solution

If I red this correctly, you're really saying that you need to return an int, but you also need to be able to detect an error. there are two common ways of doing this: putting the return value in an argument passed by reference, or adding another method to set/get errors.

For the first, it would be something like

int myfcn(int* result, char[] input) {
    // do stuff
    ...
    if( success ) {
        *result = ...;
        return ERROR_SUCCESS;
    } else {
        return ERROR;
    }
}

The second would look like...

void caller() {
    int value = TokenToInt(...);
    if( getLastError() != ERROR_SUCCESS ) {
        // handle the error
    }
}

int TokenToInt(...) {
    // do stuff
    if( error ) {
        setLastError(ERROR_WHATEVER);
        return result
    }
    return result;
}

You can look up the getLastError function for additional details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top