I have the following assignment due:

Design a class -say, fraction - that performs the arithmetic and relational operations on fractions. Overload the arithmetic and relational operators so that the appropriate symbols can be used to perform the operation. Also, overload the stream insertion and stream extraction operators for easy input and output.

Write a C++ program that, using the class fraction, performs operations on fractions.

Among other things, test the following:
Suppose x, y, and z are object of the type fraction. If the input is 2 / 3, the statement:
cin >> x; should store 2 / 3 in x. The statement:
cout << x + y << endl; should output the value of x + y in fraction form. The Statement:
z = x + y; should store the sum of x and y in z in fraction form. Your answer need not be in the lowest terms.

my question is how do you store a fraction such as 2/3 into cin>> ?

Re: Overloading operators 80 80

>my question is how do you store a fraction such as 2/3 into cin>> ?

This is one way.

#include <iostream>

int main()
{
   char slash;
   int x, y;
   std::cout << "fraction? ";
   if ( std::cin >> x &&
        std::cin >> slash &&
        std::cin >> y )
   {
      std::cout << "x = " << x << ", y = " << y << std::endl;
   }
   return 0;
}

/* my output
fraction? 2/3
x = 2, y = 3
*/
Re: Overloading operators 80 80

the whole fraction 2/3 has to be strored in the variable x. it looks as if you stored 2 in x and 3 in y. "cin >> x; should store 2 / 3 in x."

Re: Overloading operators 80 80

I don't think you'll be able to store a fraction in a single variable unless you convert it to a decimal. (ie 2/3 = .666666 ) If you need to keep it as a true fraction, then you would have a class with 2 int's, one for the numerator and one for the denominator

Re: Overloading operators 80 80

Enter the fraction as a string and use one of the many string functions like strtok() to parse the string. Numeric strings can then be converted to numbers.

Re: Overloading operators 80 80

the whole fraction 2/3 has to be strored in the variable x. it looks as if you stored 2 in x and 3 in y. "cin >> x; should store 2 / 3 in x."

Yes, but...

Design a class -say, fraction

Write a C++ program that, using the class fraction, performs operations on fractions.

Suppose x, y, and z are object of the type fraction. If the input is 2 / 3, the statement:
cin >> x; should store 2 / 3 in x.

[And winbatch has already mentioned this.]

Be a part of the DaniWeb community

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