Read a file of integers named "integers.txt". The file will consist of one number per line. For each number that you read, print to standard output a line with the number that you read, followed by a colon and a tab character, and finally the same number expressed in Roman Numerals.
I have no problems with getting the user input, but I'm not sure how to handle getting it to read text from a file of integers in addition to taking user input. Any ideas how could I program both options into main? So far, I've only covered the user input.
#include <iostream>
#include <string>
#include <stdexcept>
usingnamespace std;
// Returns the roman equivalent of n or throws an out of range exception if
// none exists.
string toRoman(int n) {
if (n <= 0) {throw out_of_range("There is no Roman equivalent");}
string numeral;
while (n >= 1000) {numeral += "M"; n -= 1000;}
if (n >= 900) {numeral += "CM"; n -= 900;}
if (n >= 500) {numeral += "D"; n -= 500;}
if (n >= 400) {numeral += "CD"; n -= 400;}
while (n >= 100) {numeral += "C"; n -= 100;}
if (n >= 90) {numeral += "XC"; n -= 90;}
if (n >= 50) {numeral += "L"; n -= 50;}
if (n >= 40) {numeral += "XL"; n -= 40;}
while (n >= 10) {numeral += "X"; n -= 10;}
if (n >= 9) {numeral += "IX"; n -= 9;}
if (n >= 5) {numeral += "V"; n -= 5;}
if (n >= 4) {numeral += "IV"; n -= 4;}
while (n >= 1) {numeral += "I"; n -= 1;}
return numeral;
}
// Prompts the user to enter an integer and displays the roman equivalent of
// the input if it can.
int main() {
int n;
cout << "Enter an integer:\n";
cin >> n;
try {
cout << n << " is " << toRoman(n) << '\n';
return 0;
} catch (out_of_range e) {
cout << "Can't process " << n << ": " << e.what() << "\n";
return -1;
}
}