On using a string with the roman character 'I' its giving 8 instead of 1. similarly 24 instead of 3 for 'III'

Viewed 59

The rest of the part which includes string like 'IV' are yet to be done, but right now the problem is for 'I' the program is returning 8 instead of 1;

#include <bits/stdc++.h> //header file
using namespace std;
  
int romantoint(char str[],int &n)
{
    int total=0;
    unordered_map <char,int> m;
    m['I'] = 1;
    m['II'] = 2;
    m['III'] = 3;
    m['IV'] = 4;
    m['V'] = 5;
    m['VI'] = 6;
    m['VII'] = 7;
    m['VIII'] = 8;
    m['IX'] = 9;
    m['X'] = 10;

    for(int i=0;i<n;i++)
    {
      total = total+m[str[i]];
    }

    return total;
    
}




int main()
{
  char str[] = "I";
  int n = strlen(str);
  cout<<romantoint(str,n);
}
1 Answers
 unordered_map <char,int> m;

This line tells the compiler that you are going to be mapping a character to an integer. Whereas when you've initialized the map, you've instead mapped the string value of 'VIII' to 8. Since the key HAS to be a character, you're actually overwriting the m['I']= 1 map when you're mapping m['VIII']=8 . This is the reason you're getting 8 when you try to find the value mapped to m['I'] since the key is NOT supposed to be anything more than a single character.

P.S this looks like a function from which you want to return the corresponding integer value taking in it's roman numeral equivalent.
I would suggest using the same unordered_map <char,int> m;map, but instead of directly mapping VIII to 8, rather use the maps from V (=5) and I (=1) to figure out the value of VIII using program logic ;)

Related