How to read text from file and accept user input as well.

My professor assigned us the following:

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.

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
#include <iostream>
#include <string>
#include <stdexcept>

using namespace 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;
  }
}
Last edited on
The assignment doesn't say anything about user input?
Anyway if you want to have both, have them one after the other.
1
2
while(file >> number) cout << toRoman(number);
while(cin >> number) cout << toRoman(number);
Topic archived. No new replies allowed.