Add to_bool(string) function

This commit is contained in:
Joakim Hove 2019-03-11 17:08:24 +01:00
parent 5421efd79d
commit 25522dc424
3 changed files with 60 additions and 1 deletions

View File

@ -105,7 +105,7 @@ namespace Opm {
*/
bool operator==(const DeckItem& other) const;
bool operator!=(const DeckItem& other) const;
static bool to_bool(std::string string_value);
private:
std::vector< double > dval;
std::vector< int > ival;

View File

@ -23,6 +23,8 @@
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <string>
#include <iostream>
#include <stdexcept>
#include <cmath>
@ -357,6 +359,43 @@ bool DeckItem::operator!=(const DeckItem& other) const {
}
bool DeckItem::to_bool(std::string string_value) {
std::transform(string_value.begin(), string_value.end(), string_value.begin(), toupper);
if (string_value == "TRUE")
return true;
if (string_value == "YES")
return true;
if (string_value == "T")
return true;
if (string_value == "Y")
return true;
if (string_value == "1")
return true;
if (string_value == "FALSE")
return false;
if (string_value == "NO")
return false;
if (string_value == "F")
return false;
if (string_value == "N")
return false;
if (string_value == "0")
return false;
throw std::invalid_argument("Could not convert string " + string_value + " to bool ");
}
/*
* Explicit template instantiations. These must be manually maintained and

View File

@ -722,3 +722,23 @@ BOOST_AUTO_TEST_CASE(DeckItemEqual) {
BOOST_CHECK( item3.equal( item5 , false, true ));
BOOST_CHECK( !item3.equal( item5 , false, false ));
}
BOOST_AUTO_TEST_CASE(STRING_TO_BOOL) {
BOOST_CHECK( DeckItem::to_bool("TRUE") );
BOOST_CHECK( DeckItem::to_bool("T") );
BOOST_CHECK( DeckItem::to_bool("YES") );
BOOST_CHECK( DeckItem::to_bool("yEs") );
BOOST_CHECK( DeckItem::to_bool("Y") );
BOOST_CHECK( DeckItem::to_bool("1") );
//
BOOST_CHECK( !DeckItem::to_bool("falsE") );
BOOST_CHECK( !DeckItem::to_bool("f") );
BOOST_CHECK( !DeckItem::to_bool("NO") );
BOOST_CHECK( !DeckItem::to_bool("N"));
BOOST_CHECK( !DeckItem::to_bool("0") );
//
BOOST_CHECK_THROW(DeckItem::to_bool("NO - not valid"), std::invalid_argument);
BOOST_CHECK_THROW(DeckItem::to_bool("YE"), std::invalid_argument);
BOOST_CHECK_THROW(DeckItem::to_bool("YE"), std::invalid_argument);
}