In: Computer Science
Write a C++ program which reads a string, less than 10
characters long. This string represents
an integer expressed in roman numbers. Let a function convert the
number from roman to
arabic form (i.e., our standard digits). Let then the main program
writes out both forms. The
roman numbers are written according to: M = 1000, D = 500, C =100,
L=50, X=10, V=5, I=1.
Examples:
LXXXVII = 87
CCXIX = 219
MCCCLIV = 1354
MMDCLXXIII = 2673
Code:
#include <bits/stdc++.h>
using namespace std;
int count(char n)
{
   if (n == 'I')
       return 1;
   if (n == 'V')
       return 5;
   if (n == 'X')
       return 10;
   if (n == 'L')
       return 50;
   if (n == 'C')
       return 100;
   if (n == 'D')
       return 500;
   if (n == 'M')
       return 1000;
   return -1;
}
//function to convert from Roman to Arabic
int convert(string& x)
{
   //initializing m=0 to store the result
   int m = 0;
   for (int j = 0; j < x.length(); j++) {
       //a[j]'s value
       int a = count(x[j]);
       if (j + 1 < x.length())
{
           // a[j+1]'s
value
           int b =
count(x[j + 1]);
           //evaluating
a and b
           if (a >= b)
{
          
    m = m + a;
           }
           else {
          
    m = m + b - a;
          
    j++;
           }
       }
       else {
           m = m + a;
       }
   }
   return m;
}
//Main
int main()
{
   //reading the string
   string x = "MMDCLXXIII";
   //if condtion to check the length of the string
   if (x.length()>10){
        //if length of the string is
greater than 10. program will print
        //invalid input
        cout<<"Invalid Input.
Input must be less than 10 characters"<<endl;
   }
   else{
        //printing the output in both
forms
   cout <<"Roman Number    Arabic
Number"<<endl;
   cout << x<<
"      
=        "<< convert(x)
<< endl;
   }
   return 0;
}
Explanation:
The above C++ program reads a string less than 10 characters which represents a Roman number
and convert it to the Arabic form
This program consists of a Function named "convert" and main function
and prints the output in both forms i.e Roman and Arabic form in the main function.
if the string is longer than 10 characters , the program will print the output as "Invalid input"
Screenshots of the Code:


Screenshots of the Output:




If the String is longer than 10 characters. Then output is:
