Converting bool to text in C++

前端 未结 15 2367
走了就别回头了
走了就别回头了 2020-12-01 04:17

Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to \"true\" and 0 turns to \"false\"? I could just use an if st

15条回答
  •  一生所求
    2020-12-01 04:31

    This should be fine:

    
    const char* bool_cast(const bool b) {
        return b ? "true" : "false";
    }
    

    But, if you want to do it more C++-ish:

    
    #include 
    #include 
    #include 
    using namespace std;
    
    string bool_cast(const bool b) {
        ostringstream ss;
        ss << boolalpha << b;
        return ss.str();
    }
    
    int main() {
        cout << bool_cast(true) << "\n";
        cout << bool_cast(false) << "\n";
    }
    

提交回复
热议问题