hi i have a project due in Two days where i have to read in a file that contains integers and roman numerals. i am pretty much done with it the only problem is my function for converting roman numeral isnt 100% correct, it wont correctly convert if it has an IV, IX, CM etc. i know what the problem is but not sure how to go about it. one solution i tried was when it got to an'I', i tried to use romanNumeral.at(i+1) so that it would move to the next position, so the program would check to see if there was a 'V' or an 'X' but i don't think that actually moved it to the next position. and then i thought about letting the whole for loop run and then once it finishes running i could use find() to find instances of IV etc in the original string and subtract the correct value from the new total, so if i had XIV i would subtract 2 to give me 14, but not sure if that is possible and it wouldnt work with just IV. any hint or possible solution would be really helpful. i really dont want to rewrite the whole function since its due in 12 hours.
You've noticed the problem is with strings like IV.
What you could do is find and replace them with a string your algorithm would like better, like IIII (which is still correct Roman Numeral, so as an added bonus your algorithm behaves properly either way).
In other words:
1. convert all strings like IV-->IIII, IX-->VIIII, XL-->XXXX, etc. 2. sum values of each 'digit'
By the way, whenever you notice you are doing the same thing over and over, you should consider using either a loop or a lookup table.
In your case, a lookup table would be useful to convert between 'digits' and digit values. For example, given the string
"IVXLCDM"
you can find the index of a 'digit' (for example, X is at position 2), then use that index to look up the corresponding value:
{ 1, 5, 10, 50, 100, 500, 1000 }
The value at index 2 is: 10. :O)
Two other things to consider.
• What if I give you a string like you find at the front of books: "vii"? • Your function name is not clear. Are you converting to or from Roman? Or both? Chose a name that represents your function best, like "convertFromRoman()".