2013-09-02 19 views
5

C++の新機能。エラー処理中に正しくループする問題がある。私はユーザーの入力が整数で、正であるかどうかをチェックしようとしています。C++整数をチェックしています。

do{ 
    cout << "Please enter an integer."; 
    cin >> n; 

    if (cin.good()) 
    { 
     if (n < 0) {cout << "Negative.";} 
     else {cout << "Positive.";} 
    } 
    else 
    { 
     cout << "Not an integer."; 
     cin.clear(); 
     cin.ignore(); 
    } 
}while (!cin.good() || n < 0); 

cout << "\ndone."; 

非整数を入力すると、ループが壊れます。 cin.clear()cin.ignore()の固有の使用法と、このループ中にcinの状態を誤解しているような気がします。 cin.ignore()を削除すると、ループは無限になります。どうしてこれなの?これをエレガントに機能するループにするために私は何ができますか?ありがとうございました。

+1

デバッガを使用してください。 –

答えて

5

非整数ブランチでは、さらにcinメソッドを呼び出すので、cin.good()がtrueにリセットされます。

あなたはこのような何かにあなたのコードを変更することができます:

while(1) { // <<< loop "forever" 
    cout << "Please enter an integer."; 
    cin >> n; 

    if (cin.good()) 
    { 
     if (n < 0) {cout << "Negative.";} 
     else { cout << "Positive."; break; } 
    }       // ^^^^^ break out of loop only if valid +ve integer 
    else 
    { 
     cout << "Not an integer."; 
     cin.clear(); 
     cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin 
    } 
} 

cout << "\ndone."; 

か、さらに、このようなことを簡素化することができます。

while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here 
{ 
    cout << "Bad input - try again: "; 
    cin.clear(); 
    cin.ignore(INT_MAX, '\n'); // NB: preferred method for flushing cin 
} 

cout << "\ndone."; 
+1

これは幻想的に動作します、ありがとう!私は自分の選択肢が私を抱きしめているとは思わなかった。私は助けと説明を感謝します。 – xavi

+0

ユーザーが迷惑メール(「abc」など)を入力すると、2番目のバージョンが無限ループになりませんか?ループする前に(しかし、 'clear()'の後に)迷惑メールを抽出(または無視)する必要があります。 –

+0

@James:良いキャッチ - ありがとう - 私は今それを修正しました(そして実際にそれをテストしました!)。 –

3
int n; 

while (!(cin >> n)||n<0)//as long as the number entered is not an int or negative, keep checking 
{ 
cout << "Wrong input. Please, try again: "; 
cin.clear();//clear input buffer 

} 
//only gets executed when you've broken out of the while loop, so n must be an int 
cout << "Positive."; 

cout << "\ndone.";//finished! 

必要な操作を行う必要があります。

+0

何が起こったか説明していません... –

+0

@ NoIdeaForName point taken、私は説明を – imulsion

+0

にコメントします。私はそれを調べます、彼は何を求めても行いません。入力が良い場合は、それが否定的な場合にのみ残すべきです... –

関連する問題