C Input only decimals

102 views Asked by At

I'm trying to restrict the input to only numerics in a simple C application however I get a warning. I suspect it's to do with the following segment. Is version one the proper way of doing things? Thanks.

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<"0" || string[i]>"9")
        valid= FALSE;
}

OR

    for(i=0;i< strlen(string); i++)
{
    if( string[i]<'0' || string[i]>'9')
        valid= FALSE;
}

rest of my code is

    void main()

{
    char number[4];
    printf("Please enter a decimal number: ");
    gets(number);   
    if (numeric(number))
        printf("'%s' is a valid number\n", number);
    else
        printf("'%s' is an invalid number\n", number);
}

To clarify I have to do the check in the fashion given according to the exercise I'm doing. Thanks.

2

There are 2 answers

2
Fred Foo On BEST ANSWER

Version one is entirely wrong. It does pointer comparisons, because string literals decay to pointers and characters are promoted to int.

Version two is close, though you should really use isdigit from <ctype.h>.

Btw., are you aware that i < strlen(string) in a loop termination condition turns linear-time algorithms into quadratic-time ones?

2
Basile Starynkevitch On

Can't you just use if (scanf ("%d", &n)==1) or call strtol ?