Converting from a std::string to bool

前端 未结 14 2638
走了就别回头了
走了就别回头了 2020-12-25 09:51

What is the best way to convert a std::string to bool? I am calling a function that returns either \"0\" or \"1\", and I need a clean solution for turning this into a boole

相关标签:
14条回答
  • 2020-12-25 10:28

    DavidL's answer is the best, but I find myself wanting to support both forms of boolean input at the same time. So a minor variation on the theme (named after std::stoi):

    bool stob(std::string s, bool throw_on_error = true)
    {
        auto result = false;    // failure to assert is false
    
        std::istringstream is(s);
        // first try simple integer conversion
        is >> result;
    
        if (is.fail())
        {
            // simple integer failed; try boolean
            is.clear();
            is >> std::boolalpha >> result;
        }
    
        if (is.fail() && throw_on_error)
        {
            throw std::invalid_argument(s.append(" is not convertable to bool"));
        }
    
        return result;
    }
    

    This supports "0", "1", "true", and "false" as valid inputs. Unfortunately, I can't figure out a portable way to also support "TRUE" and "FALSE"

    0 讨论(0)
  • 2020-12-25 10:31

    Try this:

    bool value;
    
    if(string == "1")
        value = true;
    else if(string == "0")
        value = false;
    
    0 讨论(0)
提交回复
热议问题