Search code examples
c++istream

Different input format for an object in C++


I have recently learned how to use cin with objects of a class.

istream& operator>>(istream& aliasCin, RationalNumber& r) {
    double temp;
    aliasCin >> temp;
    r = RationalNumber(temp);

    return aliasCin;
}

This is my class RationalNumber, As you can see that I am taking in a double and passing it to my non-default constructor. I know how this works but ...

My question is, I also want another style to input my Rational Number such that it is in a/b format. Where a and b are numerator and denominator of the Rational number. After I have found them I can

RationalNumber::RationalNumber (const int& a, const int& b){
    this->a = a;
    this->b = b;
    standardize(); // Changes the values of the object to standard form
    reduce(); // Changes the Rational Number to irreducible fraction
    count++;
}

First I thought of having a string as the input, finding the index of / in the string and then finding a and b, but I think there should be an easy way than this. Or is this the only option that I have?


Solution

  • Yes. you can read multiple values by chaining cin >> a >> b >> c.

    I'm not sure how to handle the slash, this seems ok:

    #include <iostream>
    
    using namespace std;
    
    int main(){
            int a;
            char separator;
            int b;
    
            cout << "Enter a fraction (e.g. 3/4): ";
            cin >> a >> separator >> b;
            cout << endl;
            if(separator=='/'){
                    //do whatever
                    cout << "Beep boop... " << a << "/" << b << "=" << (float)a/b << endl;
            }
            else{
                    cout << "wrong separator: " << separator << " a=" << a << ", b=" << b << endl;
            }
    }
    

    Sample output:

    ~$ g++ test.cpp && ./a.exe
    Enter a fraction (e.g. 3/4): 3 / 4
    
    Beep boop... 3/4=0.75