0

I am working on a project which consists of reading input from a file called input.txt which has an infinite number of lines. Each line has a roman numeral, a space, a plus or minus, another space, and then another roman numeral. I am supposed to add the two numbers together and write the answer to another file called output.txt. However, I can't think of a way to access the operator. Here is a sample input file:

XV + VII 
XII + VIII

Can someone give me an idea of how I can access the plus sign for each line of my code?

Anton Savin
  • 40,838
  • 8
  • 54
  • 90

2 Answers2

4

If you're reading the file from standard input, you can get whitespace delimited tokens by simply using the extraction operator.

#include <string>
#include <iostream>

int main(int argc, char *argv[]) {
    std::string token;
    while (std::cin >> token) {
      // parse tokens here ...

      // As an example, I'll just print out the stream of tokens.
      std::cout << token << std::endl;
    }
}

If you'd like to assume you have exactly 3 tokens per line, you can even do this:

#include <string>
#include <iostream>

int main(int argc, char *argv[]) {
    std::string first, middle, last;
    while (std::cin >> first >> middle >> last) {
      // This should print out just your operator
      std::cout << middle << std::endl;
    }
}
b4hand
  • 9,550
  • 4
  • 44
  • 49
1

1) Use string::find to find position of the split (the + or -)

2) Use string::substr to split the string into two parts according to where you find the split character.

1) Read 3 tokens from the input. First term is the left operand, second is the operator, and third is the right operand.

2) Translate the operands into integers.

3) Add or subtract the second value depending on the operator.

4) Format the result with your special roman numeral formatter.

5) Write the result to the output file.

mukunda
  • 2,908
  • 15
  • 21