我正在尝试验证用户必须输入数字的用户输入,并且必须大于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');
}
答案 0 :(得分:3)
只需将条件添加到while
,然后在循环中处理:
while ( !(cin >> income) || income < 0.0 ) {
if ( !cin )
// Clean up input stream...
else
// Must be negative number...
}