# 12+ CPP Roman to Decimal Converters

This post contains a total of 12+ Hand-Picked CPP Roman to Decimal Converter Examples with Source Code. All the roman to decimal converters are made using C++ Programming langauge.

You can use the source code of these programs for educational use with credits to the original owner.

### Related Posts

Click a Code to Copy it.

## 1. By owkss

Made by owkss. C++ Program to Convert a Roman number to Decimal. ( Source )

``````
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
std::string num, ans;
int val(0);
enum roman
{ I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 };

std::cout << "Enter roman number: " << std::endl;
std::getline(std::cin, num);
std::transform(num.begin(), num.end(), num.begin(), toupper);
ans = num;

if (num.find("IV") != std::string::npos)
val -= 2;
else if (num.find("IX") != std::string::npos)
val -= 2;
else if (num.find("XL") != std::string::npos)
val -= 20;
else if (num.find("XC") != std::string::npos)
val -= 20;
else if (num.find("CD") != std::string::npos)
val -= 200;
else if (num.find("CM") != std::string::npos)
val -= 200;

// std::reverse(num.begin(), num.end());

for (int i = 0; i < num.length(); i++)
{
switch (num.at(i))
{
case 'I':
val += I;
break;
case 'V':
val += V;
break;
case 'X':
val += X;
break;
case 'L':
val += L;
break;
case 'C':
val += C;
break;
case 'D':
val += D;
break;
case 'M':
val += M;
break;
}
}

std::cout << ans << " is " << val << std::endl;

return 0;
}``````

## 2. By JulioC OG

Made by JulioC OG. You enter a roman numeral (not case sensitive) and this code outputs its decimal equivalent. This code works fine, unless you enter roman characters in a non-roman format, for instance: VL or VX. ( Source )

``````/*

Feel free to use it anywhere and/or modify it!

I'm accustomed to low-level coding, so, it is possible that you find a shorter way to do the same.
*/
#include <iostream>
#include "string"
using namespace std;

unsigned int r2d(char r){
switch(r){
case 'I':
case 'i': return 1; break;
case 'V':
case 'v': return 5; break;
case 'X':
case 'x': return 10; break;
case 'L':
case 'l': return 50; break;
case 'C':
case 'c': return 100; break;
case 'D':
case 'd': return 500; break;
case 'M':
case 'm': return 1000; break;
default: return 255;
}
}

bool comp(unsigned int a, unsigned int b){
if(a>=b) return false;
else return true;
}

int main() {
int i=0, j=0, nGrtr=0;
int result=0;
string romanIn = "";
unsigned int romanD[20];
unsigned int romanDfinal[20]={0};
bool grtr[20];
bool error = false;

cin >> romanIn;
int t = romanIn.length();

//converts romanIn into a dec array
for(i=0; i<t; i++){
if(r2d(romanIn[i])!=255){
romanD[i]=r2d(romanIn[i]);}
else error = true;
}

if(!error){
//identifies which numbers are greater and counts them
for(i=0; i<t-1; i++){
grtr[i]=comp(romanD[i],romanD[i+1]);
if(grtr[i]) nGrtr++;
}

//create an array with all the values sorted ie, xl=40
for(i=0; i<t-nGrtr; i++){
if(grtr[j]==0){
romanDfinal[i]=romanD[j];
}else{
romanDfinal[i]=romanD[j+1]-romanD[j];
j++;
}
j++;
}

for(i=0; romanDfinal[i]; i++){
result+=romanDfinal[i];
}
cout<<result;
}else{
cout<<"Not a roman number!";
}

return 0;
}``````

``````#include<bits/stdc++.h>
using namespace std;
int value(char s)
{
switch(s)
{
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
}
return 0;
}

int romanToNo(string s)
{
int cur = 0,final = 0;
int n = s.length();
for(int i=n-1;i>=0;--i)
{
int v =value(s[i]);
if(v>=cur)
final += v;
else
final -=v;
cur = v;
}
return final;
}

int main()
{
string s;
cin>>s;
cout<<romanToNo(s);
return 0;

}``````

## 4. By Mr. Srivatsav

Made by Mr. Srivatsav. ( Source )

``````#include <iostream>
using namespace std;
int sum(char ch);

int main() {
char str[20];
cout<<"\nEnter the number in Roman(Using M,C,D,L,X,I,V): ";
cin>>str;
int i,x=0;
for(i=0;str[i]!='\0';i++)
{
if(sum(str[i])>=sum(str[i+1]))
x=x+sum(str[i]);
else
x=x-sum(str[i]);
}
cout<<"\nThe decimal number is: "<<x;

return 0;
}

int sum(char ch)
{
switch(ch)
{
case 'M': return 1000;
break;
case 'C': return 100;
break;
case 'D': return 500;
break;
case 'L': return 50;
break;
case 'X': return 10;
break;
case 'I': return 1;
break;
case 'V': return 5;
break;
}
}``````

## 5. By Davide “D0c78” Farris

Made by Davide “D0c78” Farris. ( Source )

``````#include <iostream>
using namespace std;

int main() {
string rn;
getline(cin, rn);
int rnlen = rn.size();
int rni[rnlen];
int n = 0;
for(int i = 0; i < rnlen ; i++){
switch(rn[i]){
case 'I':
rni[i] = 1;
break;
case 'V':
rni[i] = 5;
break;
case 'X':
rni[i] = 10;
break;
case 'L':
rni[i] = 50;
break;
case 'C':
rni[i] = 100;
break;
case 'D':
rni[i] = 500;
break;
case 'M':
rni[i] = 1000;
break;

}
}
for(int j = rnlen - 1; j >= 0; j--){
if(j == 0)
n += rni[j];
else{
if(rni[j] <= rni[j - 1])
n += rni[j];
else{
n += rni[j] - rni[j - 1];
j--;
}
}
}
cout<<rn<<" = "<<n;
return 0;
}``````

## 6. By Yash Chaturvedi

Made by Yash Chaturvedi. ( Source )

``````#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

int main() {
unordered_map <char,int> m=
{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100}
,{'D',500},{'M',1000}};
string no;
cin>>no;
int n=no.size();
int i,nums,sum=0;
for(i=0;i<n;)
{
if(i==n-1 ||
m[no[i]]>=m[no[i+1]])
{
nums=m[no[i]];
i++;
}
else
{
nums=m[no[i+1]]-m[no[i]];
i+=2;
}
sum=sum+nums;
}
cout<<sum;
return 0;
}``````

## 7. By Nick Pogranichnii

Made by Nick Pogranichnii. ( Source )

``````#include <iostream>
#include <string>
using namespace std;
void error(){
cout<<"invalid number";
exit(0);
}

int main() {
int i,numb,n1=0,n5=0,n10=0,n50=0,n100=0,n500=0,n1000=0,ex10=0,ex100=0;
string roman;
char Z,Y;

cin >> roman;
i=0;int n=roman.size();
while (i+1<n)
{
Z=roman.at(i);
Y=roman.at(i+1) ;
switch (Z)
{
case 'I':
if (Y=='I' && n1<3 ) {numb+=1;n1++;i++;}
else
if(Y=='V'&& n5<1 && n1<1 && roman.size()==i+2)
{numb+=4;goto label1;}
else
if(Y=='X' && n10<3 && n1<1 &&           roman.size()==i+2)
{numb+=9;goto label1;}
else error();
break;

case 'V':
if(Y=='I'){numb+=5;n5++;i++;}
else error();
break;

case 'X':
if(Y=='X' && n10<3 && ex10<1)       {numb+=10;n10++;i++;}
else
if(Y=='V' || Y=='I'){numb+=10;n10++;i++;}
else
if(Y=='C' && n100<3 && n10<1){numb-=10;n10++;i++;ex10++;}
else
if(Y=='L' && n50<1 && n10<1){numb-=10;n10++;i++;ex10++;}
else error();
break;

case 'L':
if(Y=='I' || Y=='V'){numb+=50;n50++;i++;}
else
if(Y=='X' && n10<1){numb+=50;n50++;i++;}
else error();
break;

case 'C':
if((Y=='I'|| Y=='V' || Y=='L')&& n100<3){numb+=100;n100++;i++;}
else
if(Y=='C' && n100<3 && ex100<1){numb+=100;n100++;i++;}
else
if(Y=='X' && n10<1){numb+=100;n100++;i++;}
else
if(Y=='D' && n500<1 && n100<1){numb-=100;n100++;i++;ex100++;}
else
if (Y=='M' && n1000<3 && n100<1){numb-=100;n100++;i++;ex100++;}
else error();
break;

case 'D':
if(!(Y=='M' || Y=='C')){numb+=500;n500++;i++;}
else
if(Y=='C' && ex100<1){numb+=500;n500++;i++;}
else error();
break ;

case 'M':
if(!(Y=='M' || Y=='C') && n1000<3){numb+=1000;n1000++;i++;}
else
if(Y=='M' && n1000<3 && ex100<1){numb+=1000;n1000++;i++;}
else
if(Y=='C' && ex100<1 && n1000<3 && n100<1){numb+=1000;n1000++;i++;}
break;}
}

switch (roman.at(roman.size()-1)){
case 'I':numb+=1;break;
case 'V':numb+=5;break;
case 'X':numb+=10;break;
case 'L':numb+=50;break;
case 'C':numb+=100;break;
case 'D':numb+=500;break;
case 'M':numb+=1000;break;}

label1 : cout << numb-3;
return 0;
}``````

## 8. By Atharva Deshmukh

Made by Atharva Deshmukh. The program can convert a roman number to decimal that is between 1 – 3999. ( Source )

``````/*
M C M I V =  1100+900
|

*/

#include <bits/stdc++.h>
using namespace std;

// This function returns value of a Roman symbol
int romanToDecimal(string str)
{
map<char, int> m;
m.insert({ 'I', 1 });
m.insert({ 'V', 5 });
m.insert({ 'X', 10 });
m.insert({ 'L', 50 });
m.insert({ 'C', 100 });
m.insert({ 'D', 500 });
m.insert({ 'M', 1000 });
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
cout<<"\n\ni => "<<i;
/*If present value is less than next value,
subtract present from next value and add the
resultant to the sum variable.*/
if (m[str[i]] < m[str[i + 1]])
{ cout<<"\nIf ke andar";
sum+=m[str[i+1]]-m[str[i]];
cout<<"\nsum => "<<sum;
i++;  //aage wale ke saath calculation apready ho chuka hai to ek i badha diya
continue;
}
sum += m[str[i]];
cout<<"\nsum => "<<sum;
}
return sum;
}

// Driver Code
int main()
{
// Considering inputs given are valid
string str = "IV";
cout << "\nInteger form of Roman Numeral is "<< romanToDecimal(str) << endl;

return 0;
}``````

## 9. By Pusse

Made by Pusse. In this simple program, a roman number (which stored any number of man values in a text file as strings) can be converted to it’s corresponding decimal value and it is displayed in the console. ( Source )

``````/****************************
INDEX NO    -19/ENG/082
COURSE		-PROGRAMMING QUEST
COURSE CODE -CO2210
DATE        -09/14/2021
QUEST NO    -02
*****************************/

#include <bits/stdc++.h>

using namespace std;

//Assigning roman number vals to arabic numbers in a map
map<string, int>m = { {"x",10},{"i",1},{"v",5} ,{"l",50},{"c",100} };

//Function to convert the oman number to decimal value
int romanToInt(string str) {
int n = str.length() - 1;
int val = 0, repeated = 0;
string s, s2;
for (int i = 0; i < str.length(); i++) {
s = str[i];
s2 = str[i + 1];
repeated = 0;
if (s == s2) {
for (int j = i; j < str.length(); j++) {
if (str[i] == str[j + 1]) {
repeated++;

}
else {
i = j;
break;
}
}
val += m[s] * (repeated + 1);
}
if (s != s2) {

if (m[s] > m[s2]) {
val += m[s] + m[s2];
i = i + 1;
}
else {
val += m[s2] - m[s];
i = i + 1;
}
}
}
return val;
}

//Function validate the stored roman number
bool validate(string str) {

int I=0, V=0, L=0, X=0, C=0;
string s1, s2, s3;

for (int i = 0; i < str.length(); i++) {
if (str[i] == 'x') {
X++;
}
else if (str[i] == 'i') {
I++;
}
else if (str[i] == 'v') {
V++;
}
else if (str[i] == 'l') {
L++;
}
else if (str[i] == 'c') {
C++;
}
else  {
return false;
}

}
if (X > 3 || I > 3 || V > 1 || L > 1 || C > 3 ) {
return false;
}
else {
s1 = str[0];
s2 = str[1];
if (str.length() > 2 && (m[s1] < m[s2] && str[0] != 'x')) {
return false;
}
else {
for (int i = str.length() - 1; i >= 2; i--) {
s1 = str[i];
s2 = str[i - 1];
s3 = str[i - 2];
if (m[s1] > m[s2]) {
if (m[s1] > m[s3]) {
return false;
}
}
}
}

}

}

int main()
{
string str;

cout<<"------------------Program to convert roman number into integers---------------------"<<endl;
cout<<endl;

ifstream numbers("numbers.txt");
if (!numbers) {
//Passing the error message if the file couldnt read succesfully
cout << "No file named numbers.txt found" << endl;
}else{
while (!numbers.eof()) {//reading the file until the end
numbers >> str;
cout << str << " \t:";
transform(str.begin(), str.end(), str.begin(), ::tolower);

//validating the roman number
if (validate(str)) {
cout << romanToInt(str) << endl;
}
else {
cout << "Error" << endl;
}
}
}

numbers.close();
}
``````

## 10. By HUGOW04

Made by HUGOW04. ( Source )

``````#include <bits/stdc++.h>

using namespace std;

int value(char r)
{
if(r == 'I')
{
return 1;
}
else if(r == 'V')
{
return 5;
}
else if(r == 'X')
{
return 10;
}
else if(r == 'L')
{
return 50;
}
else if(r == 'C')
{
return 100;
}
else if(r == 'D')
{
return 500;
}
else if(r == 'M')
{
return 1000;
}
return -1;
}

int romanToDecimal(string& str)
{
int res = 0;
for(int i = 0; i < str.length();i++)
{
int s1 = value(str[i]);
if(i + 1 < str.length())
{
int s2 = value(str[i + 1]);
if(s1 >= s2)
{
res = res + s1;
}
else
{
res = res + s2 - s1;
i++;
}
}
else
{
res = res + s1;
}
}
return res;
}

int main()
{
string str = "MCMIV";
cout<<str<<" converts to: "<<romanToDecimal(str)<<endl;
}``````

``````/*
* DATE       : 13-09-2021
* COURSE     : PROGRAMMING QUEST (CO2210)
* TITLE      : QUEST 02- ROMAN NUMBERS
* INDEX NO   : 19/ENG/121
*/
#include <iostream> //to access cout cin
#include <string>   //to use functions of string header
#include <fstream>  //to file handeling
#include <vector>   //to push each string into the vector
#include <sstream>
using namespace std;
/*
Note : in this programme basically were considered up to 100 roman numbers. therefore beyond 100 did not validate here
so if there is valide number greater than 100 wil also return as error.
*/
/*
Function    : digitValue
Inputs      : character
Output      : compatible decimal value
*/
int digitValue(char romanCharacter)
{
switch (romanCharacter)
{
//according to correct input then output relevent decimal value
//other than exit from the programme
case 'i' :
case 'I' : return 1;

case 'v' :
case 'V' : return 5;

case 'x' :
case 'X' : return 10;

case 'l' :
case 'L' : return 50;

case 'c' :
case 'C' : return 100;
//consider roman numbers upto 100

default  : exit(0);
}
}
/*
Function    : convertToDecimal
Inputs      : valid roman number
Output      : N/A
*/
void convertToDecimal(string roman)
{
int totValue = 0;
for (int index = 0; index < roman.length() ; index++)
{
int digit1 = digitValue(roman[index]);
if(index<roman.length()-1)
{
int digit2 = digitValue(roman[index+1]);
if(digit1>=digit2)
totValue += digit1;
//if current value greater than or equal imedeat next value add to the total value
else
totValue -= digit1;
//if current value lesser than imedeat next value substract from the total value
}
else
totValue += digit1; //last digit is alwasy add to the total value
}
//print the final value
cout << roman << " \t= " << totValue << endl;
}
/*
Function    : isValid
Inputs      : string
Output      : return true if valid roman number else return false
*/
bool isValid(string roman)
{
bool condition = true;
int index = 0;
int iCount = 0, vCount = 0, xCount = 0, lCount = 0, cCount = 0;
//puch characters into a stack
while (roman[index]!='\0')
{
char temp = roman[index];
// int current= digitValue(temp);
// int next = digitValue(roman[index + 1]);
temp=towlower(roman[index]); //convert all charaters into lower cases
//we should take each character count because, i and c can repeat only 3 times,
//v and l can't repeat and x can repeat 4 times
if(temp=='i')
iCount++;

else if(temp=='v')
vCount++;

else if(temp=='x')
xCount++;

else if(temp=='l')
lCount++;

else if(temp=='c')
cCount++;
//count each character
else
return false;
//if violte counter rule then return false
if(iCount>3 || vCount>1 || xCount>4 || lCount>1 || cCount>1)
return false;

index++;
}

//after 100 or c don't consider beyond that value therefore ci , cii ,cx ... also take as invalid
if(cCount==1 && index>1 && tolower(roman[0])!='x')
{
cout << "Can not validate beyond 100\n";
return false;
}
//now index-1 is equal to no of characters in roman number :--> A special scenario
if(xCount==4)   //if there shouldn't be 4 x value near to  --> xxxx not valid xxxix valid
{
int i=0;
while(tolower(roman[i])!='x')
{
i++;
}
if(tolower(roman[i+3])=='x')
return false;
else
condition = true;
}

//up to 100 roman numbers violate the ascending order of the dgits at
//only first character (40s and 90s) and before end(4s and 9s)
//othrewise all digits in ascending order, therefore here will return false if violate those conditions
//otherwise can't violate the descending order
for (int j = 0; j < index-1;j++)
{   //first digit is already checked therefore check with 2nd digit
int digit1 = digitValue(roman[j]);
int digit2 = digitValue(roman[j + 1]);
if(digit1<digit2)   //violate the descending order
{
//violate desecnding order at 40s and 90s, are ok
if((tolower(roman[1])=='l' || tolower(roman[1])=='c') )
{
if(index>2 && digitValue(tolower(roman[2]))>5)
return false;
else if(tolower(roman[0])=='x')
condition = true;
else
return false;
}

//at the end violate the descending order, only ix and iv
else if((tolower(roman[index-1])=='x' || tolower(roman[index-1])=='v')   )
{   //**index of the last element is index-1
if(digitValue(roman[index-2])<digitValue(roman[index-1]))
{
//if apear same value the can't apear greater vale as next vale -->iiv, iix, xxl
//tolower(roman[index - 3]) != 'i'  && tolower(roman[index - 4]) != 'i' checked that condition
if (tolower(roman[index - 2]) == 'i' && tolower(roman[index - 3]) != 'i'  && tolower(roman[index - 4]) != 'i')
condition = true;
else
return false;
}
else
{
//
if (tolower(roman[index - 2]) == 'i' && tolower(roman[index - 3]) != 'i'  && tolower(roman[index - 4]) != 'i')
condition = true;
else
return false;
}
}

else
return false;
}
else
condition = true;
}

return condition;
}

int main()
{
fstream inFile;
inFile.open("numbers.txt");
if(!inFile.is_open())
{
cout << "Can not find the file!";
exit(0);
//check whether the file is opend corrwctly. otherwise, exit from the programme
}
cout << "File Opened sucess!\n\n";  //indicate that the file is opened

vector<string> romanNumbers;
string dat, num;
stringstream str;
while(!inFile.eof())
{
inFile >> dat;
romanNumbers.push_back(dat);    //push roman numbers into the vector
}

for (int index = 0; index < romanNumbers.size(); index++)
{
if(isValid(romanNumbers[index]))    //check the validity of each roman number
convertToDecimal(romanNumbers[index]);    //call the convertor
else
cout << romanNumbers[index] << " \t= error\n";
}
return 0; //end of the programme :-)
}``````

## 12. By Stushar

Made by Stushar. ( Source )

``````#include<bits/stdc++.h>
using namespace std;

int roman_to_decimal(string s)
{
unordered_map<char, int> T = { { 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 } };

int n=s.size();
int sum=T[s[n-1]];

for(int i=n-2;i>=0;i--)
{
if(T[s[i]]<T[s[i+1]])
sum-=T[s[i]];
else
sum+=T[s[i]];
}

return sum;

}

int main()
{
string s="VIII";
cout<<roman_to_decimal(s);
}``````

## 13. By geoff-pitman

Made by geoff-pitman. ( Source )

``````// Problem: Convert Roman numerals to decimal equivalent
// C++ Solution
// 9/4/2016

#include<iostream>
#include<string>
#include<fstream>
#include<map>

using namespace std;

int main()
{

/************************   VARIABLE DECLARATIONS  *******************/
// holds in-file in ifstream variable
ifstream inf;

// output stream variable we will use to write to a file
ofstream outf;

// total sum of current roman numeral string
int decimalSum = 0;

// current value being looked at
int currentVal = 0;

// keeps track of highest value looked at
int maxVal = 0;

// holds current string of roman numerals
string numerals = "";

// create associative array for roman numerals
map<char, int> roman;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;
/*********************************************************************/

// open file to read from
inf.open("roman_numerals.txt");

// open file to write to
outf.open("output_numerals.txt");

// In the code below,  inf >> numerals , will read characters and put them in the
// buffer stream until it hits white space. The stream is then inserted into the
// string variable ' numerals ' .  The body of the loop will then execute.
// When the end of the file is reached the operator>>() function will flag false,
// which kills the loop.
//
// !!!!! Don't forget that operators are functions in C++ !!!!!!
// inf >> numerals is the same as operator>>(inf, numerals)

while (inf >> numerals)
{
for (int i = numerals.length()-1; i >= 0; i--)
{
// numerals[i] resolves to a char, which is passed to the associative array, roman[ ]
currentVal = roman[numerals[i]];

if (currentVal == maxVal)
decimalSum += currentVal;
if (currentVal < maxVal)
decimalSum -= currentVal;
if (currentVal > maxVal)
{
decimalSum += currentVal;
maxVal = currentVal;
}
}

// output to console
cout << endl << numerals << " translated to decimal equivalent -> "
<< decimalSum << endl;

// write the same output to file
outf << endl << numerals << " translated to decimal equivalent -> "
<< decimalSum << endl;

decimalSum = 0;
currentVal = 0;
maxVal = 0;
}

// close output file stream
outf.close();

return 0;
}``````