#ifdef TEST_PROGRAM #include #include #endif // TEST_PROGRAM #include static const char rc[] = { 'I', 'V', 'X', 'L', 'C', 'D', 'M' }; static const int rMin(1), rMax(3999); std::string roman( int dec ) { static const size_t bufSize = 24; // Returns a std::string containing the representation, in Roman // numerals, of the decimal number "dec". "rMin" and "rMax" define // the range we can represent with the numerals defined in "rc". if (dec < rMin || dec > rMax) return "Out of range"; char buf[bufSize]; const char * pc = rc; char * last = buf + bufSize; *--last = '\0'; do { if (int digit = dec % 10) { int ni = digit % 5; if (ni == 4) { if (digit == 4) *--last = *(pc+1); else *--last = *(pc+2); *--last = *pc; } else { switch (ni) { case 0: *--last = *(pc+1); break; case 1: case 2: case 3: while (ni--) *--last = *pc; if (digit > 4) *--last = *(pc+1); break; } } } dec /= 10; pc += 2; } while (dec); return last; } #ifdef TEST_PROGRAM int main( int argc, char * argv[] ) { if (argc == 1) { std::cerr << "Usage:\t" << argv[0] << " i1 [ ,i2 [ ,i3 [ " << "... ]]]\n\n\tConverts the command line " << "arguments (numbers in the range " << rMin << "..." << rMax << ")\n\tto Roman numerals.\n"; } else { while (--argc) { int i = std::atoi(*++argv); std::cout << i << "\t==> " << roman(i) << std::endl; } } } #endif // TEST_PROGRAM