2011-09-29 47 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... 
}