开发者

how to restrict an input in c

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 开发者_JAVA技巧C


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;
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜