Determining if a string is a double

前端 未结 5 708
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 01:38

I would like to see if a string contains a double as its sole contents. In other words, if it could possibly be the output of the following function:

string          


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 02:26

    You can use the Boost lexical_cast to check whether a string contains double or not.

    #include  
    ....
    using boost::lexical_cast; 
    using boost::bad_lexical_cast; 
    ....
    template bool isValid(const string& num) { 
       bool flag = true; 
       try { 
          T tmp = lexical_cast(num); 
       } 
       catch (bad_lexical_cast &e) { 
          flag = false; 
       } 
       return flag; 
    } 
    
    int main(){
      // ....
     if (isValid(str))
         cout << "valid double." << endl; 
     else 
         cout << "NOT a valid double." << endl;
      //....
    }
    

提交回复
热议问题