Converting from a std::string to bool

前端 未结 14 2637
走了就别回头了
走了就别回头了 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:22

    There is also std::stoi in c++11:

    bool value = std::stoi(someString.c_str());

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

    It'll probably be overkill for you, but I'd use boost::lexical_cast

    boost::lexical_cast<bool>("1") // returns true
    boost::lexical_cast<bool>("0") // returns false
    
    0 讨论(0)
  • 2020-12-25 10:23
    bool to_bool(std::string const &string) { 
        return string[0] == '1';
    }
    
    0 讨论(0)
  • 2020-12-25 10:25

    Here's a way similar to Kyle's except it handles the leading zeroes and stuff:

    bool to_bool(std::string const& s) {
         return atoi(s.c_str());
    }
    
    0 讨论(0)
  • 2020-12-25 10:25

    If you need "true" and "false" string support consider Boost...

    BOOST_TEST(convert<bool>( "true", cnv(std::boolalpha)).value_or(false) ==  true);
    BOOST_TEST(convert<bool>("false", cnv(std::boolalpha)).value_or( true) == false);
    
    BOOST_TEST(convert<bool>("1", cnv(std::noboolalpha)).value_or(false) ==  true);
    BOOST_TEST(convert<bool>("0", cnv(std::noboolalpha)).value_or( true) == false);
    

    https://www.boost.org/doc/libs/1_71_0/libs/convert/doc/html/boost_convert/converters_detail/stream_converter.html

    0 讨论(0)
  • 2020-12-25 10:26
    bool to_bool(std::string const& s) {
         return s != "0";
    }
    
    0 讨论(0)
提交回复
热议问题