//
// begin of file roman.cpp
//
#include
#include
#include
#include
#include "roman.hpp"
static char *table1[] = {
"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"
};
static char *table10[] = {
"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"
};
static char *table100[] = {
"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"
};
Roman::Roman(void)
{
n = 0;
str = NULL;
}
//
// Roman Constructor from an integer
//
Roman::Roman(int n0)
{
char str0[50];
int n1;
n = n0;
if (n = 5000) {
str = NULL;
}
else {
n1 = n0;
*str0 = 0;
while (n1 >= 1000) {
strcat(str0, "M");
n1 -= 1000;
}
strcat(str0, table100[n1 / 100]);
n1 %= 100;
strcat(str0, table10[n1 / 10]);
n1 %= 10;
strcat(str0, table1[n1]);
str = strdup(str0); // problem: keeps killing memory...
}
}
//
// Roman Constructor from a string
//
Roman::Roman(char *str0)
{
int n1;
int k;
char *s;
str = strdup(str0); // kills memory :-(
s = str0;
n1 = 0;
while (*s == 'M') { // get all M's
n1 += 1000;
s++;
}
for (k = 9; k >= 1; k--) {
if (!strnicmp(s, table100[k], strlen(table100[k]))) {
n1 += k * 100;
s += strlen(table100[k]);
break;
}
}
for (k = 9; k >= 1; k--) {
if (!strnicmp(s, table10[k], strlen(table10[k]))) {
n1 += k * 10;
s += strlen(table10[k]);
break;
}
}
for (k = 9; k >= 1; k--) {
if (!strnicmp(s, table1[k], strlen(table1[k]))) {
n1 += k * 1;
s += strlen(table1[k]);
break;
}
}
n = n1;
}
//
// Roman Destructor. As I used "strdup", now I must use free
//
Roman::~Roman(void)
{
free(str);
}
//
// Roman output
//
ostream& operator<<(ostream& Out, Roman& R)
{
Out << R.str;
return Out;
}
//
// Roman input
//
istream& operator>>(istream& Inpu, Roman& R)
{
char str0[50];
Inpu >> str0;
R = Roman(str0);
return Inpu;
}
int main(void)
{
// Test case
//
Roman R0(666), R1("MCMXCVII"), R2;
char str[1000];
cout << "666 = " << R0 << " = " << R0.n << '\n';
cout << "1997 = " << R1 << " = " << R1.n << '\n';
for (;;) {
cout << "Enter any roman number (1 to terminate): ";
cin >> R2;
cout << R2 << " = " << R2.n << '\n';
if (R2.n == 1)
break;
}
return EXIT_SUCCESS;
}
//
// end of roman.cpp
//
---
þ SLMR 2.1a þ Amicus certus in re incerta cernitur (Cicero)
--- FMail/386 1.02
---------------
* Origin: CentroIn! +55-21-205-0281, 41 lines, 24h, RJ/Brazil (4:802/21)
|