2011-09-29 39 views
0

我想驗證用戶輸入的用戶必須輸入的數字,它必須大於0,只有數字的驗證我得到它的工作;不過,我似乎無法納入大於0如何驗證用戶輸入的數字和大於0的數字

float income; 
cout << "How much did you earn last year: "; 

    //validating imput for income 
    while(!(cin >> income)) 
    { 
     char ch; 
     cin.clear(); 
     cout << "Sorry, number must be biger than \"0\" \n" 
       << "How much did you make last year: "; 
     while(cin.get(ch) && ch != '\n'); 
    } 

回答

3

的驗證只需將條件添加到while,並在循環處理:

while (!(cin >> income) || income < 0.0) { 
    if (!cin) 
     // Clean up input stream... 
    else 
     // Must be negative number... 
}