我是C ++的新手,我想知道我是否可以就我遇到的问题寻求帮助。 Im给出的输入为A / B类型的分数或整数值。我需要将A和B值分开,以便可以将它们放在fracnum和fracdnum变量中。当im给定一个整数值时,就会出现问题。这是我的代码:

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

最佳答案

老实说,这是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
}

关于c++ - 给定斜杠时分母和分子输入c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28575950/

10-12 22:22