15

私は宿題のためにこのコードを書いています (C++ を始めたばかりなので、簡単に行ってください)。今日、while、do-while、および for ループを開始したところです。プログラムが整数を要求するときに文字を入力すると、プログラムが無限ループすることを除いて、プログラムは正常に実行されます。何が起こっている?(以下のコード) ***編集:明確にするために、ループしている部分は次のとおりです。「入力した数値は負です。続行するには正の数値を入力してください。」ただし、ユーザーは別の番号を入力する機会が与えられません。これを印刷し続けるだけです。

    #include <iostream>
using namespace std;

int main ( )
{
    //define variables
    int num1, num2, total;
    char answer1;

    do
    {
        //user enters a number
        cout << "\nPlease enter a positive number and press Enter: \n";
        cin >> num1;

        //check that the given num1 value is positive
        while (num1 < 0)
        {
            cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
            cin >> num1;
        }

        cout << endl;

        //add the sum of 1 through num1 value
        num2 = 1;
        total = 0;
        while (num1 >= num2)
        {
            total = total + num2;
            num2 ++;
        }

        //tell the user the sum
        cout << "The total of all the integers\nfrom 1 to " << num1 << " is: \n";
        cout << total;

        //ask if the user wants to try again
        cout << "\n\nWould you like to try again with a new number?\nEnter y for yes or n for no.\n";
        cin >> answer1;
    } while (answer1 == 'y');   

    cout << endl;
    return 0;
}
4

4 に答える 4

1

この答えはあなたの問題を解決するはずです。基本的に、ストリームから文字を読み取ろうとしていますが、int に解析できないため、ストリームはエラー状態のままになります。

エラーをチェックしてクリアし、それに応じて対応する必要があります。

于 2013-10-22T15:03:11.737 に答える