替换o / istream bool bitshift运算符

时间:2012-07-01 22:11:00

标签: c++ stream boolean operator-keyword bit-shift

我想替换i / ostream的bitshift bool重载。当前实现仅接受输入字符串“0”或“1”并仅输出“0”或“1”。我想做一个考虑其他序列的bool重载,例如“t”,“true”,“f”,“false”等等......反正有没有做到这一点,即使它只限于有限的范围?这是我想要使用的代码:

inline std::ostream& operator << (std::ostream& os, bool b)
{
    return os << ( (b) ? "true" : "false" );
}

inline std::istream& operator >> (std::istream& is, bool& b)
{
    string s;
    is >> s;
    s = Trim(s);

    const char*  true_table[5] = { "t", "T", "true" , "True ", "1" };
    const char* false_table[5] = { "f", "F", "false", "False", "0" };

    for (uint i = 0; i < 5; ++i)
    {
        if (s == true_table[i])
        {
            b = true;
            return is;
        }
    }

    for (uint i = 0; i < 5; ++i)
    {
        if (s == false_table[i])
        {
            b = false;
            return is;
        }
    }

    is.setstate(std::ios::failbit);
    return is;
}

1 个答案:

答案 0 :(得分:1)

如果您愿意放弃tf,可以使用std::boolalphastd::noboolalpha

来自cppreference

// boolalpha output
std::cout << std::boolalpha 
          << "boolalpha true: " << true << '\n'
          << "boolalpha false: " << false << '\n';
std::cout << std::noboolalpha 
          << "noboolalpha true: " << true << '\n'
          << "noboolalpha false: " << false << '\n';
// booalpha parse
bool b1, b2;
std::istringstream is("true false");
is >> std::boolalpha >> b1 >> b2;
std::cout << '\"' << is.str() << "\" parsed as " << b1 << ' ' << b2 << '\n';

输出:

boolalpha true: true
boolalpha false: false
noboolalpha true: 1
noboolalpha false: 0
"true false" parsed as 1 0