views:

220

answers:

3

I want to prevent my program from any other types of input instead of int. How to check the type of an input without assigning it to a variable? in C

+1  A: 

you should put it into a char variable (or a string) check it's validity, and then put it to the int var. you have to read the data to somewhere.

Dani
+3  A: 

See strtod, strtol and friends.

All of those function take an out parameter (generally referred to as endptr) which shows you where the conversion ended. You can use that information to decide if the input you wanted to convert was an integer or floating point number or not a number at all.

The strategy is to try to parse the input as a base 10 long. If that does not work (i.e. if there were unconverted characters), see if parsing it as a double works. If neither works, the input is not a number. Clearly, you would have to decide what basic type you would want to use for numbers. You can build in more checks and refinements, but here is a simple example.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

struct a_number {
    unsigned char is_long;
    union {
        double d;
        long i;
    };
};

int main(void) {
    int n;
    char *input_strings[3] = {
        "1234","1234.56", "12asdf"
    };

    struct a_number *numbers[3];

    for (n = 0; n < 3; ++n) {
        char *start = input_strings[n];
        char *end;
        long i = strtol(start, &end, 10);
        if ( *end == '\0' ) {
            struct a_number *num = malloc(sizeof(*num));
            assert( num );
            num->is_long = 1;
            num->i = i;
            numbers[n] = num;
        }
        else {
            double d = strtod(start, &end);
            if ( *end == '\0' ) {
                struct a_number *num = malloc(sizeof(*num));
                assert( num );
                num->is_long = 0;
                num->d = d;
                numbers[n] = num;
            }
            else {
                numbers[n] = NULL;
            }
        }
    }

    for (n = 0; n < 3; ++n) {
        if ( numbers[n] ) {
            if ( numbers[n]->is_long ) {
                printf("%ld\n", numbers[n]->i );
            }
            else {
                printf("%g\n", numbers[n]->d );
            }
        }
    }

    return 0;
}
Sinan Ünür
A: 

Without assigning the input to a variable you cannot possibly do this.

Kinopiko