0

我想替换 i/ostream 的 bitshift bool 重载。当前的实现只接受“0”或“1”的输入字符串,只输出“0”或“1”。我想制作一个考虑其他序列的布尔重载,例如“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;
}
4

1 回答 1

1

如果您愿意放弃t并且f作为可能性,您可以使用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
于 2012-07-01T22:17:30.813 回答