I need to write a program that changes a Roman Numeral to a numeric value.
I've been inputing the roman numeral "CCLXXXVII", expecting it to output "287". Instead I've been getting "7101".
Here is my code:
#include <iostream>
#include <string>
using namespace std;
const int VALUE_I = 1;
const int VALUE_V = 5;
const int VALUE_X = 10;
const int VALUE_L = 50;
const int VALUE_C = 100;
const int VALUE_D = 500;
const int VALUE_M = 1000;
void sendValue(string& , int&);
int main(){
string romanNumeral;
int romanNumeralValue;
cout << "Enter a Roman Numeral: ";
cin >> romanNumeral;
sendValue(romanNumeral, romanNumeralValue);
cout << endl << "Value of the Roman Numeral: " << romanNumeralValue;
return 0;
}
void sendValue(string & a, int & b){
int stringLength = a.length();
int count = 0;
b = 0;
string temp;
while(count < stringLength){
temp = a.substr(count , count + 1);
if(temp == "I")
b += VALUE_I;
else if(temp == "V")
b += VALUE_V;
else if(temp == "X")
b += VALUE_X;
else if(temp == "L")
b += VALUE_L;
else if(temp == "C")
b += VALUE_C;
else if(temp == "D")
b += VALUE_D;
else
b += VALUE_M;
count++;
}
}
We need to use functions for this program. Here are the values I got for string temp:
When count = 0 : temp = "C"
When count = 1 : temp = "CL"
When count = 2 : temp = "LXX"
When count = 3 : temp = "XXXV"
When count = 4 : temp = "XXVII"
When count = 5 : temp = "XVII"
When count = 6 : temp = "VII"
When count = 7 : temp = "II"
When count = 8 : temp = "I"