1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
#include <iostream>
#include <cstring>
#include <string>
#include <locale>
using namespace std;
int main()
{
int deciNum; //Converted Decimal Number
char choice; //User's choice for what is displayed
int size = 0; //Size of array
char check[15]; //Array to hold user entered roman numerals
bool ok = false;
//Get the roman numeral from user for conversion.
cout << "Enter a roman numeral: ";
cin.getline(check, 15);
cout << "numbered entered: " << check << endl;
for (int i = 0; i < 15; i++)
{
if (check[i] != '\0')
size++;
else
i = 15;
}
//Convert to upper case
for (int i = 0; i < size; i++)
{
check[i] = toupper(check[i]);
}
cout << "numeral converted to uppercase: " << check << endl;
int values[] = { 1000, 500, 100, 50, 10, 5, 1 }; //Arrary to hold roman numerals
int romanNum[] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' }; //Arrary to hold values of roman numerals
//loop through string, if all are valid roman numeral
for (int i = 0; i < size; i++)
{
ok = false;
for (int y = 0; y < 7; y++)
{
if (check[i] == romanNum[y]) //Check to see if all numbers are valid Roman Numerals
{
ok = true;
}
}
if (ok = false) //If an incorrect numeral was entered, ask user to re-enter their number.
{
cout << check[i] << " is not a valid Roman Numeral." << endl;
cout << "Please try again. " << endl;
cin.getline(check, 15);
}
}
//Fill array with converted decimal values
int numbers[15] = { 0 };
for (int x = 0; x < size; x++)
{
for (int y = 0; y < 7; y++)
{
if (check[x] == romanNum[y])
{
numbers[x] = values[y];
}
}
}
cout << "array of numbers: " << numbers << endl;
//loop through and add up numbers, checking for subtractives like 'IV'.
for (int i = 0; i < size;)
{
if (numbers[i] < numbers[i + 1]) //if subtractive, subtract number from next, add to total, advance loop by 2
{
deciNum += numbers[i + 1] - numbers[i];
i += 2;
}
else // if number is repeated or greater than, add to total
{
deciNum += numbers[i];
i++;
}
}
// Ask user if she would like to display the roman numeral or the decimal form?
cout << "Would you like to see your number as a decimal or a roman numeral?" << endl;
cout << "Enter 'D' for decimal and 'R' for roman numeral : " <<endl;
cin >> choice;
// Display the number in the form chosen by the user.
if (choice == 'R' || choice == 'r')
{
cout << "You entered: " << check << endl;
}
else
{
cout << "The Roman Numeral " << check << " translates to: " << deciNum << endl;
}
cin.get();
cin.get();
return 0;
}
|