The code is really long so I don't want to post all of it, but I'm posting the part I'm having an issue with. This is part of a fraction class I'm writing. Most of it is working but for there is something wrong with the istream because when I enter a fraction it just says d=0.
This is my input overload:

istream& operator>>(istream& in, fraction& x)
    int a;
    int b;
    char c;
    in >> a >> c >> b;
    fraction z=(a/b);
    return in;

This is the part in main:

fraction d;
    cout << "Enter a fraction: ";
    cin >> d;

    cout << "d=" << d << endl;

What am I doing wrong?

Recommended Answers

All 4 Replies

My guess is that it is reading a/b as one thing. Have you tried entering a / b instead? Also note that you do integer division, so if a is less than b you will get zero as your value.

A quick glance at the definition of the overloaded istream and it's clear that you've missed the fact that dividing two integers will lead to a loss of precision. Change int b; to float b; and you're good to go (provided class fraction stores a fraction as a floating-point value, and has the necessary constructor). You could also typecast the division to promote either the numerator (a) or denominator (b) to a float or double value.

Hope this helps!

I don't know what float is. We never learned that. I tried changing them to double but that didn't help.

never mind. i figured it out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.