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;
}
编译运行如下:



你可能感兴趣的:(C++,类型转换,String)