Operator overloading

I am trying to overload the extraction operator for my rationals class to be able to accept input as whole numbers, mixed fractions((1, 1/2) = 3/2), regular fractions as well as percentages but so far I've only got the regular fractions to work. Not too sure what's not right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::istream& operator>> (std::istream& in, Rational& r) {
	int n, d;
	if (in >> n && in.peek() == '/' && in.ignore() && in >> d) {
		r = Rational(n, d);
	}
	else if (in >> n && in.peek() == '%' && in.ignore()){
        d = 100;
        r = Rational(n, d);
	}
	else if (in >> n){
        d = 1;
        r = Rational(n, d);
	}
	return in;
}
Last edited on
You need to build the input string first, then you can parse it.

You build the input string by peeking (as you've done), or by using unget(), to see if the next character is one you're interested in. You're interested in numbers and the first '/'.

You split the string into the numerator and denominator by looking for the './' and taking the string of numbers either side of it. If it's missing, the denominator is 1.

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
std::istream& operator>>(std::istream&is, Rational& n)
{    
    // read input
    std::string input_str;

    bool want_separator = true;
    char ch;
    while (is.get(ch))
    {
        if ('0' <= ch && ch <= '9')
        {    
            input_str.append(ch);
            continue;
        }

        if (want_separator && ch == '/')
        {    
            input_str.append(ch);
            want_separator = false;
            continue;
        }

        is.unget(ch);
        break;
    }

    // parse input_str and fill in n
    // an exercise for the reader

    // done
    return is;
}   
Last edited on
I'm not sure I understand how the numerator and denominator will be created after the input has been built into the input_str. Could you please elaborate a bit more
Not really; well, not yet anyway.

Have you looked at the string that comes in? I haven't tested my parser, so it probably doesn't work, but it should. In any event, it was written to present the idea.

I mean if you had a string that looked like "12", what do you think the numerator and denominator ought to be, and what would the algorithm to generate it look like? And how about "123/45"?
Topic archived. No new replies allowed.