Question

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?

Était-ce utile?

La 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;
}

Autres conseils

Once again, I need to split a value like "22/34" into 22 and 34, using only iostream and iomanip.

Couldn't you just read in the first integer, use get to get the next character, and then read the second integer? Something like this:

#include <iostream>

int main() {
    using std::cin;
    using std::cout;

    int num;
    int den;

    while(cin) {
        cin >> num;
        if (cin.get() != '/') {
            // handle error
        }   
        cin >> den;

        cout << num << "/" << den << std::endl;
    }   

    return 0;
}

You can then make sure that the character read between the two integers was a '/' and handle appropriately if it isn't.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top