Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program to read in a string of characters that represent a Roman numeral

ID: 3544280 • Letter: W

Question

Write a program to read in a string of characters that represent a Roman

numeral and then convert it to Arabic form (an integer). The character values

for Roman numerals are as follows:

M 1000

D 500

C 100

L 50

X 10

V 5

I 1

Test your program on the following data :

LXXXVII (87), CCXIX (219), MCCCLIV (1354), MMDCLXXIII (2673), MCDLXXVI (1476)

LXXXVII

50 + 10 +10+10+5+1+1

CCXIX

100 +100 +10 +1 +10 -1 -1

M 1000

D 500

C 100

L 50

X 10

V 5

I 1

MCCCLIV

1000 + 100 + 100 + 100 + 50 + 1 +5 - 1 -1

MMDCLXXIII

1000 + 1000 + 500 + 100 + 50 + 10 + 10 +1 + 1 +1

MCDLXXVI

1000+100+500-100-100+50+10 + 10+5+1

You must use at least one function.

LXXXVII

CCXIX

MCCCLIV

MMDCLXXIII Cpsc1103 week 6 notes page 2 of 3

MCDLXXVI

?save file when cursor is on the next line


pseudo codes:

start

allocate variables

initialize files

while not end of file

read ch ins.get(ch);

sum = 0;

while (ch !=

Explanation / Answer

Here you go. you problems had to do with not resetting total and previous back to 0 when you read a new number.
here is the working version :

#include <iostream> //keyboard I/O
#include <fstream> //external file streams
#include <conio.h> //getch()
#define in_file "data.txt"
using namespace std;

int main()
{
ifstream ins; //ins as output stream

//define variables
int total = 0,//total value of numbers
current, //current character
previous = 0; //previous character
char ch, //string to be read
M, D, C, L, X, V, I;

//open files
ins.open(in_file);

while (!ins.eof())
{
ins.get(ch); //read ch from file

while (ch!=' ')
{
switch (ch)
{
case 'M': current = 1000;
break;
case 'D': current = 500;
break;
case 'C': current = 100;
break;
case 'L': current = 50;
break;
case 'X': current = 10;
break;
case 'V': current = 5;
break;
case 'I': current = 1;
break;
} //end switch statement

if (previous >= current)
total += current;
else
total += current - (2*previous) ;

previous = current;
ins.get(ch);

} //end inner while loop
cout << endl;
cout << total;
total = 0;
previous = 0;
} //end outer while loop

ins.close();
getch();
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote