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

后端 未结 4 1487
忘了有多久
忘了有多久 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:23

    Perhaps the strtod() function can be of help here, as it tells you how much has been converted:

    const char * buf = get_raw_data(); // somehow
    
    char * endptr;
    const double value = strtod(buf, &endptr);
    
    if (endptr != buf + std::strlen(buf))  { /* ... error ... */ }
    

    As the source for buf you could tokenize your input with std::string token; std::cin >> token; or something like that and use token.c_str().

提交回复
热议问题