Hey guys, i was looking through the internet for ways on how to solve converting roman numerals into integers and i found this method which is confusing me as im not able to understand it.

using namespace std;
int main()
{

  
    char rom;
    int n = 0;
    int tot = 0 ;
    int i;

 
    cout << "Enter the roman numerals to convert" << endl;
    while (rom !=  ""){
	 cin.get(rom);

     
        if(rom=='M' || rom=='m')
{
  tot=tot+1000;
}
else if(rom=='D' || rom=='D')
{

  tot=tot+500;
}
  else if(rom=='C' || rom=='C')
{
  tot=tot+100;
}
  else if(rom=='L' || rom=='l')
{

  tot=tot+50;
}
  else if(rom=='X' || rom=='x')
{

  tot=tot+10;
}
  else if(rom=='V' || rom=='v')
{

  tot=tot+5;
}
else if(rom=='I' || rom=='i')
{

  tot=tot+1;

}
     }
        cout<<"The value in Roman numerals is "<<tot<<endl;

}

from what i read up , cin.get basically reads one character at a time. So for example, if i were i were to type in "DDX" , it will read D then D again and finally X.

What i am really confused is how do they do the calculation. if one character is run through the if statement at a time, there should be a calculation error as for example, if i were to input in "CD" which actually means 400, the program will read "C" first which is 100 , followed by "D" , which is 500. so when it adds up , it should be 600? but when i tried running it with this coding, it manages to calculate 400. Anybody can explain which part am i wrong? or help explain how this coding works?

Are you sure that this is the EXACT code you're running? Because this line: while (rom != "") shouldn't even compile...

Sorry, i pasted the copy i edited. should be while

(rom != ' ')

.

Sorry, i pasted the copy i edited. should be while .

Even that will not compile...
Fixing this while loop and running the program gives me the 'expected'
600 output, so I'm not sure what you're doing...(It is impossible to get 400 with CD as input).

Enter the roman numerals to convert
CD
The value in Roman numerals is 600

Anyway, I think the point of this code that you found is that it only converts one Roman numeral at a time and add it to the total... or the guy who wrote this doesn't know how Roman numerals work (as there are only additions in the code.. how would it ever work?)

Internet Code Lesson #1:
a) If you want to llearn how to do a task by looking at code
b) If the code you found doesn't work
z) Do not use it. Find something else.

Why bother with it if IIIX == 13. What can you learn?

yep. i solved this problem using another method. but im just curious how it worked as when it run it, it could get the correct answer so i was quite perplexed on how it could work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.