|
-
March 3rd, 2011, 03:59 AM
#9
Re: 0 Converting Roman Numerals to Decimals
I may be mistaken, but your first iteration of convert2roman seemed to work. I actually found the solution clever too.
When you write functions like convert2roman, it is usually pretty easy to get them to work for valid input. The hard implementation is the one that tells you when it fails.
Anyways, here is a wikipedia inspired implementation:
Code:
#include <iostream>
#include <string>
int roman_2_decimal(const std::string& i_string)
{
static const std::string roman[] = {"M", "CM", "CD", "D", "C", "XC", "XL", "L", "X", "IX", "IV", "V", "I"};
static const int decimal[] = { 1000, 900, 400, 500, 100, 90, 40, 50, 10, 9, 4, 5, 1};
static const size_t size = sizeof(decimal)/sizeof(decimal[0]);
int value = 0;
size_t index = 0;
for(int i = 0; i<size; ++i)
{
while(i_string.substr(index, roman[i].length()) == roman[i])
{
value += decimal[i];
index += roman[i].length();
}
}
return value;
}
int main()
{
std::cout << "MCXIV" << ": " << roman_2_decimal("MCXIV") << std::endl;
std::cout << "CCCLIX" << ": " << roman_2_decimal("CCCLIX") << std::endl;
std::cout << "MDCLXVI" << ": " << roman_2_decimal("MDCLXVI") << std::endl;
}
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|