0

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
  • What form of input are you talking about? Input from the console? Input from a file? Input over the network? Commented Nov 8, 2009 at 12:19

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.