Hello, this is a simple Roman Numeral Converter
It works too! However, it displays weird numbers if you enter anything below 0.
I have also made some mistake that whenever a digit is above 4000, it still uses my cout and displays- The Roman Numeral for this is: Please enter a number between 1-3999.
Also, is there any way I can rewrite or manipulate this code so that I start off with int main() ?
Thanks, everybody!!
#include<iostream>
#include<string>
using namespace std;
string intToRoman(int num)
{
string roman; //setting up string
int thousand,hundred,ten,one; //declaring thousand, hundred, ten, and one for later
const char *ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"}; //Defines ones as 1-9 in RN
const char *tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; //Defines tens as 10-90 in RN
const char *hundreds[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; //Defines hundreds as 100-900 in RN
const char *thousands[] = {"","M","MM","MMM","MMMM",}; //Defines thousands as 1000-4000 in RN
if (num <= 4000) //Number can't be greater than 4000
{
thousand = num / 1000;
num = num % 1000; //Get rid of 1000s
hundred = num / 100;
num = num % 100; //Get rid of 100s
ten = num / 10;
one = num % 10;
roman += thousands[thousand]; // using the string roman
roman += hundreds[hundred];
roman += tens[ten];
roman += ones[one];
}
else
{
roman = "Please enter a number between 1-3999. \nThank you!\n";
return roman;
}
}
int main()
{
int num;
cout<<"What number would you like to convert between 1 and 3999? ";
cin>>num;
string output = intToRoman(num);
cout<< "The Roman Numeral for this number is: " << intToRoman(num);
you can make roman an invalid sentinel value and check that in main...
else
{
roman = "Please enter a number between 1-3999. \nThank you!\n";
return "bad!";
}
...
string output = intToRoman(num);
if(output != "bad!")
cout<< "The Roman Numeral for this number is: " << intToRoman(num);
// you already printed an error, but it is better design to print the errors in main only and remove the error from the function. that way users can print a custom message for bad data, if someone were to re-use the code, for one example of the reasons.