Search code examples
c++operator-overloadingiostreamfractionsiomanip

Mixed number class istream issues


I assigned myself some homework over the summer, and the project I am 98% finished with has come to a standstill due to this one problem.

I have a class called Mixed. It contains member data for a whole number, a numerator, and a denominator. I need to overload all of the common operators to allow multiplication, addition, comparison and streaming of objects of type Mixed. I have all the operators overloaded except for >> (the extraction operator).

All mixed numbers read in will be of format: whole numerator/denominator

ex: 1 2/3, 0 7/8, -3 18/5, 0 -1/89

Header: friend istream& operator>> (istream &, Mixed);

CPP file: istream& operator>> (istream &in, Mixed m) {...}

For the assignment, I am limited to the iostream and iomanip libraries. My plan was to read in the values from the stream and assign them to temporary int variables (w, n, d) which I would then use with the Mixed constructor to create object m. Unfortunately, I cannot think of a way to separate the numerator and denominator. They are both ints, but they have a char (/) between them.

  • I cannot use getline() with its delimiter, because it assigns data to a char array, which I do not believe I can convert to an int without another library.
  • I cannot use a char array and then segment it for the same reason.
  • I cannot use a while loop with get() and peek() because, again, I do not think I will be able to convert a char array into an int.
  • I cannot use a string or c-string and then segment it because that requires external libraries.

Once again, I need to split a value like "22/34" into 22 and 34, using only iostream and iomanip. Is there some fairly obvious method I am overlooking? Is there a way to implicitly convert using pointers?


Solution

  • You could first extract the nominator, then the separating character, and then the denominator.

    Example for illustration:

    istream& operator>> (istream &in, Mixed &m) {
        int num, denom;
        char separ;
    
        in >> num;
        in.get(separ);
        if (separ != '/')
          in.setstate(ios::failbit);
        in >> denom;
    
        if (in) {
          // All extraction worked
          m.numerator = num;
          m.denominator = denom;
        }
    
        return in;
    }