2016-10-15 4 views
0

cinが有効な入力を受け取ったかどうかを調べようとしていますが(例えば、int変数の文字列もcharもありません)、whileループは無限ループで停止し、whileループがユーザ入力を待っていない(データ型が無効である)

How many would you like to buy ? fdssd 
Sorry, you must enter an integer (asks for usr input here) 

実際の結果:

How many would you like to buy ? fdssd 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
+1

ような何か。 –

答えて

2

した後も、ユーザーの入力

#include <iostream> 
#include <string> 
using namespace std; 
int main(){ 
    cout << "How many would you like to buy ? "; 
    int buyAmt; 
    cin >> buyAmt; 
    while (!cin) { 
     cin.clear(); 
     cin >> buyAmt; 
     cout << "Sorry, you must enter an integer" << endl << endl; 
    } 
} 

期待される結果を待ちますcin.clear();を適用する場合は、最初に間違った入力を消費してから、cin >> buyAmt;を再度適用する必要があります。

あなたは `のstd :: cin.ignore()を読み取ることができませんでし`問題の文字べき

while (!cin) { 
    std::string dummy; 
    cin.clear(); 
    cin >> dummy; 
    cout << "Sorry, you must enter an integer" << endl << endl; 
    cout << "How many would you like to buy ? "; 
    cin >> buyAmt; 
} 
関連する問題