!cin 和 !(cin >> xxx)
!cin,判断上一次的输入是否失败(bad input)
!(cin >> xxx)判断当前输入是否失败(bad input)
实例
int fill_array(double ar[], int limit)
{
using namespace std;
double temp;
int i;
for (i = 0; i < limit; i++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;
if (!cin) // bad input ,判断temp是否是double类型的数据,若不是,则进入循环语句
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input, input process terminated.\n";
break;
}
else if (temp < 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
cout << "Enter revaluation factor: ";
double factor;
while (!(cin >> factor)) // bad input,判断facotr是否是double类型的数据,若不是,则进入循环语句
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; please enter a number: ";
}