Using strtol to validate integer input in ANSI C

前端 未结 3 2238
梦如初夏
梦如初夏 2021-01-14 07:23

I am new to programming and to C in general and am currently studying it at university. This is for an assignment so I would like to avoid direct answers but are more after

3条回答
  •  醉酒成梦
    2021-01-14 07:57

    The function strtol returns long int, which is a signed value. I suggest that you use another variable (entry_num), which you could test for <0, thus detecting negative numbers.

    I would also suggest that regex could test string input for digits and valid input, or you could use strtok and anything but digits as the delimiter ;-) Or you could scan the input string using validation, something like:

    int validate_input ( char* input )
    {
        char *p = input;
        if( !input ) return 0;
        for( p=input; *p && (isdigit(*p) || iswhite(*p)); ++p )
        {
        }
        if( *p ) return 0;
        return 1;
    }
    

提交回复
热议问题