4

バグは cin.getline ( string, 25, '\n' ); から始まります。またはその下の行 (strtod)。cin を使えばうまくいきますが、やめることはできません。double 以外を入力すると、無限ループが実行されます。助けが必要。基本的に、最初の繰り返しが実行され、入力を求められないため、ユーザーは数学の問題を間違えます。2回目の繰り返しはうまくいきます。そして、次もいいです。q を使用してバックアウトすると、モード セレクターに戻されます。モードを選択すると、最初の繰り返しでバグが再発します。次の繰り返しではなくなりました。

int main()
{
    char choice, name[25], string[25], op;
    int operator_number, average, difference, first_operand, second_operand, input, answer, total_questions = 0, total_correct = 0;
    double dfirst_operand, dsecond_operand, dinput, danswer, percentage;
    bool rounding = false;

    srand ( time(NULL) );

    cout << "What's your name?\n";
    cin.getline ( name, 25, '\n' );
    cout << '\n' << "Hi, " << name << ".";

    do {
    do {
    cout << "\nWhich math operations do you want to practice?\n  1. Addition\n  2. Subtraction\n  3. Multiplication\n  4. Division\n  5. Mixed\n  6. Difference of squares multiplication.\nChoose a number (q to quit).\n";
    cin >> choice;
    } while( choice < '1' || choice > '6' && choice!= 'q');

    cout << "\n";

    switch(choice) {
    case '1':
            while( string[0]!= 'q') {
                dfirst_operand = rand() % 15 + 1;
                dsecond_operand = rand() % 15 + 1;
                danswer = dfirst_operand + dsecond_operand;
                cout << dfirst_operand << " + " << dsecond_operand << " equals?\nEnter q to quit.\n";
                cin.getline ( string, 25, '\n' );
                dinput = strtod( string,NULL);
                //cin >> dinput;
                if(string[0]!='q') {
                ++total_questions;
                if(dinput==danswer) {
                    ++total_correct;
                    cout << "Correct. " << total_correct << " correct out of " << total_questions << ".";
                } else {
                    cout << "Wrong. " << dfirst_operand << " + " << dsecond_operand << " equals " << danswer << ".\n" << total_correct << " correct out of " << total_questions << ".";
                };
                percentage = floor(10000 * (float) total_correct / total_questions)/100;
                cout << ' ' << percentage << "%.\n\n";
                }
            }
            break;
            }
    } while(choice!='q');
    return 0;
}
4

2 に答える 2

1

問題は次の行です。

 cin >> choice;

この行は、整数に変換できる文字入力の入力バッファーを解析します。したがって、次のように入力すると:

2<newline>

文字列 "2" が変換さ<newline>れ、入力バッファーに残ります。したがって、後続の cin.getline() はすぐに満たされます。

これが、JonH の提案が機能しない理由でもあります。入力に入力バッファをパージする必要がありcin << choiceます。別の方法は、すべての入力に cin.getline() を使用することです (または、C-string ではなく std::string で動作する ::getline() を使用することをお勧めします)。フォーマットされた入力スキャンが必要です。

ただし、この問題を解決するために cin.ignore() を使用する必要がある場合は、次のようにする必要があります。

cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;

std::numeric_limits はヘッダーで定義されています。あなたのソリューションは、ユーザーが 25 文字を超えて入力しないことを信頼しています。これはあまり安全な仮定ではありません。

于 2010-03-05T21:50:20.030 に答える
0

cin.ignore()の直後または直前にを投げてみてくださいcin.getline()

于 2010-03-05T20:21:53.883 に答える