给出斜杠c ++时分离分母和分子输入

时间:2015-02-18 04:24:22

标签: c++ input istream fractions

我对C ++比较陌生,我想知道我是否可以获得有关我一直存在的问题的帮助。我将输入作为A / B类型的一部分或整数值。我需要将A和B值分开,以便将它们放入fracnum和fracdnum变量中。当给出一个整数值时,问题就来了。这是我的代码:

istream& operator >>(istream& in,  Fraction& frac){
    char slash = '/' ;
    int fracnum;
    int fracdnum;
    int peekchar;
in >>fracnum;
if(in >> slash){
    in >>fracdnum;
}
else{
    in.putback(slash);
    fracdnum = 1;
}

    frac = Fraction(fracnum, fracdnum);
    return in;
    }

我不知道如何分割两个分数并处理整数。

编辑*****

我尝试过使用scanf方法,但它仍然无法正常工作,这是我的尝试,有人注意到它有什么问题吗?

istream& operator >>(istream& in,  Fraction& frac){
int fracdnum;
int fracnum;
int num_read = scanf("%d/%d", &fracnum, &fracdnum);
if( num_read ==1){
    fracdnum=1;
Fraction(fracnum,fracdnum);
}
else if (num_read == 2){
    Fraction(fracnum,fracdnum);
}

    return in;
    }

这是我用于该程序的测试文件:

    // Test input, exception and +=:
    Fraction sum(0);
    Fraction fin;
    cout << "\nSumming fractions. Enter fractions as \"1/2\" or just enter a single integer." << endl;
    cout << "Enter zero to end the summation:" << endl;
    do {
        cout << "Enter a fraction to add to sum: ";
        try {
            cin >> fin;
            sum += fin;
        } catch (FractionException &e) {
            cout << e.what() << endl;
        }
    } while (fin != 0);
    cout << "Sum is: " << sum << endl;


    return 0;

} // end main

2 个答案:

答案 0 :(得分:1)

老实说,这是scanf更容易的情况:

int num_read = scanf("%d/%d", &fracnum, &fracdnum);
if(num_read == 1) {
    // scanf read one number
    fracdnum = 1;
} else if(num_read == 2) {
    // scanf read two numbers
} else {
    // scanf read nothing: fail
}

答案 1 :(得分:0)

看看你的scanf尝试,是的,有很多错误。

istream& operator>>(istream& in, Fraction& frac)
{
    int fracdnum;
    int fracnum;

到目前为止一切正常,但拼写除外。

    int num_read = scanf("%d/%d", &fracnum, &fracdnum);

哎呀,你刚刚从stdin而不是in阅读。

    if( num_read ==1){
        fracdnum=1;
        Fraction(fracnum,fracdnum);

哎呀,你创建了一个临时的Fraction对象并再次扔掉它。

    }
    else if (num_read == 2){
        Fraction(fracnum,fracdnum);

同样的问题

    }

    return in;
}

这应该更好:

istream& operator >>(istream& in,  Fraction& frac)
{
   int fracdenom;
   int fracnum;

   std::string inputline;
   if (getline(in, inputline)) {
       int num_read = sscanf(inputline.c_str(), "%d/%d", &fracnum, &fracdenom);
       if (num_read > 0) {
           if (num_read < 2) {
               fracdenom=1;
           }
           frac = Fraction(fracnum,fracdenom);
       }
       else {
           in.setstate(std::ios::failbit);
       }
   }
   return in;
}

如果您希望空格作为终结符,请使用in >> inputline代替getline(in, inputline)