簡體   English   中英

重載輸入運算符。 簡單分數 class

[英]Overloading input operator. Simple fraction class

假設我有一些簡單的 class 稱為 Fraction

class Fraction {
    public:
        int num, den;
}

我想要做的是能夠使用cin >>用值填充這個 class 的實例。

我已經搞定了

friend istream & operator>>(istream &in, Fraction &fr){
   char slash = 0;
   in >> fr.num>> slash >> fr.den;  
   return in;
}

它在傳遞4/3等分數時效果很好。

我現在需要做的是能夠使用cin >>傳遞像1 2/3這樣的分數。 我怎樣才能做到這一點? 我嘗試將此 stream 轉換為字符串並檢查空格,如果存在空格,則將全部部分視為新分數,然后將這兩個部分相加,但我無法使這件事起作用。

我當前的代碼

friend istream & operator>>(istream &in, Fraction&fr){

    if( false ){
        char slash = 0;
        in >> ul.num>> slash >> ul.den; 
    }else{
        char slash = 0;
        char space = 0;
        int total = 0;
        int numer= 0;
        int denom = 0;
        in >> total >> numer>> slash >> denom ;
        Fraction tot(total), res;
        fr.setNum(numer);
        fr.setDen(denom );
        res = tot + fr;
        fr.setNum(res.num);
        fr.setDen(res.den);
    }
    return in;
}

...

Fraction f1;
cin >> f1;

有誰知道如何做到這一點? 我的好像太復雜了。 干杯

讀第一個數字。 嘗試閱讀第二個數字。 如果失敗,重置並假設第一個數字是數字。 然后嘗試閱讀斜線。 如果成功,請閱讀 denom。

char slash = 0;
int total = 0;
int numer= 0;
int denom = 0;

if (in >> total) { // could also be numer
    // Try to read numer
    if (!(in >> numer)) {
        // Error - could be slash or error
        in.clear();
        numer = total;
        total = 0;
    }
    // Get slash
    while (in >> slash && std::isspace(slash));
    if (in && slash == '/') {
        if (in >> denom) {
            // success
            fr.setNum(denom * total + numer);
            fr.setDen(denom);
            return in;
        }
    }
}
// If here, error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM