Home > Software design >  Program that converts from roman to arabic numerals always gives Invalid Argument
Program that converts from roman to arabic numerals always gives Invalid Argument

Time:05-19

I have this program that tries to convert from Roman numerals to Arabic numerals and compiles without problems, but even if I enter a valid number, it always comes out by default saying Invalid argument.

#include <conio.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main () {
   int Rnum = 0;
   int Rdec = 0;
   int cont = 0;
   int cont3R = 0;
   int Rnums[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   char Rletter = ' ';
   char roman[15] = "";
   printf ("Enter a Roman numeral in the range I to MMMCMXCIX:\n");

while block

   while ((Rletter != 'n') && (cont < 15)) {
      Rletter = toupper(getchar());
      switch (Rletter) {
         /* V, L and D can only appear once */
         case 'V': case 'L': case 'D':
            if ((cont > 0) && (roman[cont - 1] == Rletter)) {
                  printf ("\nInvalid argument");
                  sleep(1000);
                  exit(0);
            }

            else { roman[cont  ] = Rletter; }
            break;

         case 'I': case 'X': case 'C': case 'M':
            if (cont3R <= 3) {
               roman[cont  ] = Rletter;
            }
            cont3R  ;
            if ((cont3R > 3) && (roman[cont - 2] == Rletter)) {
               printf ("\nInvalid argument");
               sleep(1000);
               exit(0);
            }
            if ((cont > 1) && ((cont3R > 3) || (roman[cont - 2] != Rletter))) {
               cont3R = 1;
            }
            break;

         case 'n':   break;

         default:    printf("\nInvalid argument"); //<--- It comes out here
                     sleep(1000);
                     exit(0);
     }
   }

CodePudding user response:

You don't specify the input, but I presume you're using the character 'n' to terminate the roman numeral.

However, the loop check:

while ((letraR != 'n') && (cont < 15)) {

and the switch case:

case 'n': break;

will never match because you've already called toupper() on the input.

So you probably just need these to check for 'N' rather than 'n'.

  • Related