Reputation: 43
I'm trying to read different formats as csv and json. One time boolean value is given by string "1" or "0" and another time by string "true" or "false". Now i use uniform template function that converts that string to bool. but std::istream can't read both bool formats simultaneously. If flag std::ios::boolalpha is set, exception grows while reading "1" and vise versa. I want to read both ways, and i don't know what format is now.
Upvotes: 2
Views: 3684
Reputation: 393467
You can always just use a local stream to read it:
bool read_bool(std::istream& is) {
std::istream local(is.rdbuf());
// now the default stream options are in force
bool v;
if (!local >> v)
throw std::runtime_error("parse error");
Otherwise, you can choose to parse your input manually:
std::string s;
if (is >> s) {
if (s == "0" || s == "false")
//
else if (s == "1" || ...
etc.
You can also use something like
Boost Spirit
qi::symbols<char, bool> table;
table.add("0",false)("1",true)("false",false)("true",true);
bool v;
if (is >> qi::match(table, v))
std::cout << "Parsed: " << v << "\n";
Upvotes: 3