Converting from a std::string to bool

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

    Write a free function:

    bool ToBool( const std::string & s ) {
       return s.at(0) == '1';
    }
    

    This is about the simplest thing that might work, but you need to ask yourself:

    • what should an empty string return? the version above throws an exception
    • what should a character other than '1' or '0' convert to?
    • is a string of more than one character a valid input for the function?

    I'm sure there are others - this is the joy of API design!

提交回复
热议问题