Is this the correct approach to do input validation with floating point values?

后端 未结 4 1489
忘了有多久
忘了有多久 2021-01-22 11:26

After spending a good amount of time researching input validation, I combined a few ideas and came up with this:

Function to check a string for a valid dou

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 12:07

    I'm not sure about "the" correct way, but it's certainly not how I'd do it. First and probably most obvious, this chunk of code:

        for (i = 0, d = 0; i < BUFFSIZE && buffer[i] != 0 && buffer[i] >= '0' &&
                 buffer[i] <= '9' || (buffer[i] == '.' && d == 0); i++)
                if (buffer[i] == '.') ++d;
    

    is duplicated in a couple of places (at least I think the other instance is identical, and probably should be anyway).

    Second, you don't appear to allow numbers like 1e23 or -1.2, which are usually accepted as floating point.

    Offhand, I think I'd use strtod to attempt to convert the input. You can use its second parameter to detect whether a conversion reached the end of the input string (if not, you'll know at least part of the input wasn't accepted). You'll then (apparently) want to check that the returned value was in the desired range.

提交回复
热议问题