2015-07-21 39 views
0

我想驗證用戶輸入。如果用戶輸入除整數外的任何數據,則應保留在While循環中。但是當我給程序一個「w」時,例如程序只是無休止地打印「請輸入整數」,我不得不停止程序。爲什麼我在驗證用戶輸入時得到一個無限循環?

int MAns1 = 0 
while (!(cin >> MAns1)) 
{ 
    cout << "\nPlease Enter An Integer: "; 
    cin.clear(); 
} 
+0

這是完全重複的。我的錯。我也想通了: 而((CIN >> MAns1)!) \t \t \t { \t \t \t \t的cout << 「\ n請輸入一個整數:」; \t \t \t \t cin.clear(); \t \t \t \t cin.ignore(INT_MAX,'\ n'); \t \t \t} – RIDDLEisVoltron

回答

0

因爲您應該測試(cin >> MAns1)而不是!(cin >> MAns1)。我會做這樣的事情:

#include<iostream> 
using std::cin; 
using std::cout; 

int main() { 
    int MAns1 = 0; 
    for (;;) 
    { 
     cout << "\nPlease Enter An Integer: "; 
     cin >> MAnsi; 

     // did the last read succeed? 
     if(!cin) { 
      // it did *not* succeed. 
      break; 
     } 
    } 
} 
相關問題