我想替换 i/ostream 的位移布尔重载。当前实现仅接受"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;
}
如果你愿意放弃t
并f
作为可能性,你可以使用std::boolalpha
和std::noboolalpha
从 CPP 首选项:
// 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