2014-03-02 121 views
0

我試圖驗證我的用戶輸入使用while循環。請參閱下面的代碼/ while循環。我希望他們輸入一個浮點數,我試圖驗證他們輸入了一個數字,而不是一個字母/句子。我認爲這個循環應該工作,但是當我運行它時,如果我輸入一個數字,它會在達到程序結束前彈出,如果我輸入一個字符串,它會觸及cout語句,但無法請求cin,然後驗證循環。如果你能解釋什麼和爲什麼發生以及如何解決它,我會非常感激。使用cin關閉while循環

#include <iostream> 
using namespace std; 

int main() 
{ 
    float mph, i = 0; 
    cout << "this program will calculate the distance a train will travel in a given amount of time." << endl; 
    cout << "What is the speed of the vehicle in mph? "; 
    cin >> mph; 
    cout << endl; 


    while (mph > -3.4E-38 && mph < 3.4E38); 
    { 
     cout << "that is not a number, do not pass go, do not collect $200 but DO try again." << endl; 
     cin >> mph; 
     // trace statement to check whats happening in the loop 
     cout << "trace: " << mph << "faluer: " << i << endl; 
     i++; 
    } 
    cout << "works twice" << endl; 

    system("pause"); 
    return 0; 
} 
+0

拉斐爾,我想我有點下架你的意思(我是新的C++),但也許我問錯了問題。我試圖做的是以最簡單的方式驗證用戶輸入。我要求用戶提供數字,我想用while語句來檢查他是否輸入了一個數字,不管它是整數還是浮點數,只要它不是字符串或字符。用while語句做這件事的最好方法是什麼?我認爲我的一段時間的聲明是這樣做的,但也許這不是最好的方式去做呢?驗證用戶輸入數字的最佳方法是什麼? – James

+0

如果你指的是Raphael發佈的答案,那麼這正是它所做的,他解釋了它是如何工作的 –

回答

3

你應該改變你的代碼中while循環裏面是這樣的:

cout<<"that is not a number, do not pass go, do not collect $200 but DO try again."<<endl; 

if (!cin) { // we enter the if statement if cin is in a "bad" state. 
    cin.clear(); // first we clear the error flag here 
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // now we skip the input, 
                    // that led to the invalid state 
} 

cin>>mph; 
如果輸入一個字符串並嘗試將其讀入與 cin一個 float

cin進入無效狀態,並拒絕讀取任何輸入直到清除。
這就是我上面提出的代碼試圖解決的問題。請注意,您必須包含<limits>才能正常工作。

相關鏈接獲取更多信息,清除輸入流:Why is this cin reading jammed?