C++ bool和string转换

直接贴代码吧。用g++能够编译。測试ok


#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char **argv)
{
    bool a = true;

    ostringstream os1;
    os1 << a;
    cout << string(os1.str()) << endl;

    ostringstream os2;
    a = false;
    os2 << a;
    cout << string(os2.str()) << endl;

    stringstream ss1;
    ss1 << true;
    cout << ss1.str() << endl;

    stringstream ss2;
    ss2 << false;
    cout << ss2.str() << endl;

    bool b;  
    string s = "true";  
    istringstream(s) >> boolalpha >> b;
    cout << "b = " << b << endl;

    s = "false";
    istringstream(s) >> boolalpha >> b;
    cout << "b = " << b << endl;
    
    return 0;
}
编译执行例如以下:



原文地址:https://www.cnblogs.com/gavanwanggw/p/6724689.html