/********************************************************************************************
example 4 -- roman.cpp
Implementation for class roman.
********************************************************************************************/
#include "roman.h"
ostream& operator<<(ostream& out, const roman& R) {
out << R.asString();
return out;
}
// ------- display tool -------
string roman::asString() const {
int value = number;
string converted = "";
if (value < 1) {
converted = "underflow";
return converted;
}
else if (value > 3888) {
converted = "overflow";
return converted;
}
else {
for (int i=0, stop = value/1000; i < stop; i++) {
value -= 1000;
converted += 'M';
}
switch (value/100) {
case 0:
break;
case 9:
value -= 900;
converted += "CM";
break;
case 4:
value -= 400;
converted += "CD";
break;
case 8: case 7: case 6: case 5:
value -= 500;
converted += 'D';
//fall through and do 3, 2 & 1!!!
default:
for (int i=0, stop=value/100; i < stop; i++) {
value -= 100;
converted += 'C';
}
}
switch (value/10) {
case 0:
break;
case 9:
value -= 90;
converted += "XC";
break;
case 4:
value -= 40;
converted += "XL";
break;
case 8: case 7: case 6: case 5:
value -= 50;
converted += 'L';
//fall through and do 3, 2 & 1!!!
default:
for (int i=0, stop=value/10; i < stop; i++) {
value -= 10;
converted += 'X';
}
}
switch (value) {
case 0:
break;
case 9:
converted += "IX";
break;
case 4:
converted += "IV";
break;
case 8: case 7: case 6: case 5:
value -= 5;
converted += 'V';
//fall through and do 3, 2 & 1!!!
default:
for (int i=0; i < value; i++)
converted += 'I';
}
return converted;
}
}