C++ bool和string转换

来源:互联网 发布:杭州seo整站优化 编辑:程序博客网 时间:2024/06/02 13:12

直接贴代码吧,用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;}
编译运行如下:



0 0