#include #include #include #include #include using namespace std; /* Lookup table mapping Roman numerals digits to numeric values */ map table; /* Convert string representing or Roman number to decimal value */ int roman2decimal(string const &roman) { int last_digit = 1000; int sum = 0; for(int i = 0; i < roman.size(); i++) { /* SANITY CHECK: Check that only valid Roman numerals are used */ if(table.find(roman[i]) == table.end()) { cerr << "Invalid Roman numeral in string: " << roman << endl; throw; } /* Lookup the numeric value of this Roman numeral */ int this_digit = table[roman[i]]; /* Check if subtractive rule should have been used on last_digit */ if(this_digit > last_digit) { sum -= 2 * last_digit; } sum += this_digit; last_digit = this_digit; } return sum; } /* Main body of program */ void process(void) { int roman_num; /* Read how many Roman numbers to convert */ cin >> roman_num; /* Convert all Roman numbers from input to their decimal equivalent */ for(int i = 0; i < roman_num; i++) { string roman; cin >> roman; cout << roman2decimal(roman) << endl; } } /* Run program and print out any exceptions that occur */ int main(void) { /* Initialize lookup table for roman2decimal() */ table['M'] = 1000; table['D'] = 500; table['C'] = 100; table['L'] = 50; table['X'] = 10; table['V'] = 5; table['I'] = 1; /* Throw exceptions on failed data extraction in >> operator */ cin.exceptions(ios::failbit); /* Run main body of code */ try { process(); } /* Catch unexpected EOF or bad input data */ catch(ios::failure const &e) { cerr << "Unexpected EOF or data type mismatch on input" << endl; } return 0; }