C++ IsFloat function

前端 未结 18 1313
不思量自难忘°
不思量自难忘° 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:58

    [EDIT: Fixed to forbid initial whitespace and trailing nonsense.]

    #include 
    
    bool isFloat(string s) {
        istringstream iss(s);
        float dummy;
        iss >> noskipws >> dummy;
        return iss && iss.eof();     // Result converted to bool
    }
    

    You could easily turn this into a function templated on a type T instead of float. This is essentially what Boost's lexical_cast does.

提交回复
热议问题