/// // Copyright (C) 2002 - 2004, Fredrik Arnerup & Rasmus Kaj, See COPYING /// #include "stringutil.h" #include #include #include template<> bool to(const std::string& value) { if(value == "true" || value == "1") return true; if(value == "false" || value == "0") return false; throw std::runtime_error("Bad value: \"" + value + "\" for bool"); } template<> std::string tostr(const bool& b) { return b? "true": "false"; } bool whitespace(char c) { return std::isspace(c); } std::string strip_whitespace(std::string s, bool front, bool back) { int b=0; int l=s.length()-1; while(front && b<=l && whitespace(s[b])) b++; while(back && l>=0 && whitespace(s[l])) l--; return s.substr(b, l-b+1); } bool starts_with(const std::string& str, const std::string& start) { std::string::size_type len = start.length(); return str.length() >= len && str.substr(0, len) == start; } std::istream &safe_getline(std::istream &in, std::string &line) { // treat "\n" "\r" "\r\n" and "\n\r" the same way line = ""; char c; while(in.get(c)) { switch(c) { case '\r': if(in && in.peek() == '\n') in.get(); return in; break; case '\n': if(in && in.peek() == '\r') in.get(); return in; break; default: line += c; break; } } return in; } std::string to_xml(const std::string str) { std::ostringstream msg; for(std::string::const_iterator i = str.begin(); i != str.end(); ++i) if((*i == '<') || (*i == '>') || (*i == '&')) msg << "&#" << int(*i) << ';'; else msg << *i; return msg.str(); } std::string to_roman(int num) { if(num < 1 || num > 3999) throw std::runtime_error("The number " + tostr(num) + " could not " "be converted to a roman numeral"); char symbols[] = "??mdclxvi"; char *sym_off = symbols; char *reps[] = {"", "2", "22", "222", "21", "1", "12", "122", "1222", "20"}; std::string result; int order = 1000; for(int i = 3; i >= 0; i--) { char *rep = reps[num / order]; while(*rep) {result += sym_off[*rep - '0']; rep++;} num %= order; order /= 10; sym_off++; sym_off++; } return result; }