home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / ROMAN2L.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  76 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  ROMAN2L.C Covert roman numerals to long integers.
  5. **
  6. **  public domain by Bob Stout
  7. */
  8.  
  9. #include <ctype.h>
  10. #include "sniptype.h"
  11.  
  12. struct numeral {
  13.       long val;
  14.       int  ch;
  15. };
  16.  
  17. static struct numeral numerals[] = {
  18.       {    1L, 'I' },
  19.       {    5L, 'V' },
  20.       {   10L, 'X' },
  21.       {   50L, 'L' },
  22.       {  100L, 'C' },
  23.       {  500L, 'D' },
  24.       { 1000L, 'M' }
  25. };
  26.  
  27. /*
  28. **  roman2long() - Converts a roman numeral string into a long integer
  29. **
  30. **  Arguments: 1 - Roman numeral string
  31. **
  32. **  Returns: Long value if valid, else -1L
  33. */
  34.  
  35. long roman2long(const char *str)
  36. {
  37.       int i, j, k;
  38.       long retval = 0L;
  39.  
  40.       if (!str || NUL == *str)
  41.             return -1L;
  42.       for (i = 0, k = -1; str[i]; ++i)
  43.       {
  44.             for (j = 0; j < 7; ++j)
  45.             {
  46.                   if (numerals[j].ch == toupper(str[i]))
  47.                         break;
  48.             }
  49.             if (7 == j)
  50.                   return -1L;
  51.             if (k >= 0 && k < j)
  52.             {
  53.                   retval -= numerals[k].val * 2;
  54.                   retval += numerals[j].val;
  55.             }
  56.             else  retval += numerals[j].val;
  57.             k = j;
  58.       }
  59.       return retval;
  60. }
  61.  
  62. #ifdef TEST
  63.  
  64. #include <stdio.h>
  65.  
  66. int main(int argc, char *argv[])
  67. {
  68.       while (--argc)
  69.       {
  70.             ++argv;
  71.             printf("roman2long(%s) returned %ld\n", *argv, roman2long(*argv));
  72.       }
  73. }
  74.  
  75. #endif /* TEST */
  76.