C++ IsFloat function

前端 未结 18 1315
不思量自难忘°
不思量自难忘° 2020-12-09 15:58

Does anybody know of a convenient means of determining if a string value \"qualifies\" as a floating-point number?

bool IsFloat( string MyString )
{
   ... e         


        
18条回答
  •  没有蜡笔的小新
    2020-12-09 16:43

    The main issue with other responses is performance

    Often you don't need every corner case, for example maybe nan and -/+ inf, are not as important to cover as having speed. Maybe you don't need to handle 1.0E+03 notation. You just want a fast way to parse strings to numbers.

    Here is a simple, pure std::string way, that's not very fast:

    size_t npos = word.find_first_not_of ( ".+-0123456789" );
    if ( npos == std::string::npos ) {
       val = atof ( word.c_str() );
    }
    

    This is slow because it is O(k*13), checking each char against 0 thur 9

    Here is a faster way:

    bool isNum = true;
    int st = 0;
    while (word.at(st)==32) st++;    // leading spaces
    ch = word.at(st);
    if (ch == 43 || ch==45 ) st++;   // check +, -
    
    for (int n = st; n < word.length(); n++) {
      char ch = word.at(n);
      if ( ch < 48 || ch > 57 || ch != 46 ) {
         isNum = false;
         break;   // not a num, early terminate
      } 
    }
    

    This has the benefit of terminating early if any non-numerical character is found, and it checks by range rather than every number digit (0-9). So the average compares is 3x per char, O(k*3), with early termination.

    Notice this technique is very similar to the actual one used in the stdlib 'atof' function: http://www.beedub.com/Sprite093/src/lib/c/stdlib/atof.c

提交回复
热议问题