I want to replace the bitshift bool overload for i/ostream. The current implementation only takes in input strings of “0” or “1” and outputs only “0” or “1”. I want to make a bool overload that considers other sequences such as “t”,”true”,”f”,”false”, etc… Is there anyway to do this, even if its confined to a limited scope? This is the code I want to use:
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;
}
If you’re willing to drop
tandfas possibilities you can just usestd::boolalphaandstd::noboolalphafrom cppreference:
Output: