Determining if a string is a double

前端 未结 5 700
伪装坚强ぢ
伪装坚强ぢ 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:08

    You've been offered C-style and boost alternatives, but in the style of your doubleToString implementation:

    bool is_double(const std::string& s)
    {
        std::istringstream iss(s);
        double d;
        return iss >> d >> std::ws && iss.eof();
    }
    

    Here, you're checking iss >> d returns iss, which will only evaluate to true in a boolean context if the streaming was successful. The check for nothing but whitespace before eof() ensures there's no trailing garbage.

    If you want to consider leading and trailing whitespace garbage too:

        return iss >> std::nowkipws >> d && iss.eof();
    

    This can be generalised into a boolean-returning test similar to boost's lexical_cast<>...

    template 
    bool is_ws(const std::string& s)
    {
        std::istringstream iss(s);
        T x;
        return iss >> x >> std::ws && iss.eof();
    }
    
    template 
    bool is(const std::string& s)
    {
        std::istringstream iss(s);
        T x;
        return iss >> std::noskipws >> x && iss.eof();
    }
    
    ...
    if (is("3.14E0")) ...
    if (is("hello world")) ...; // note: NOT a single string
                                             // as streaming tokenises at
                                             // whitespace by default...
    

    You can specialise the template for any type-specific behaviours you'd like, such as:

    template <>
    bool is(const std::string& s)
    {
        return true;
    }
    

提交回复
热议问题